Quickly convert simpleXMLObject to STDClass? - php

Does anybody know a quick way to convert a SimpleXMLElement to a normal STDClass object, without iterating through each branch manually? I would feel better working with a normal object after fetching the data.

$my_std_class = json_decode(json_encode($my_simplexmlelement));
$my_assoc_array = json_decode(json_encode($my_simplexmlelement), true);

I suggest looking into using XMLReader, which lends itself well to extracting data and storing it as whatever data type one wishes, instead of SimpleXML. It's especially good for regularly-used documents (I use it, extended as RSSReader, for RSS), is much faster than might be expected, and as a bonus uses less memory than SimpleXML.

Another way is:
(object)(array)$my_simplexmlelement
Unfortunately if you have children they remain as SimpleXMLElement

I don't know if there's a way to convert the object without iterating through it. My guess is that you can't.
You can check this thread out, it shows you how to convert a SimpleXML to an array, you can adapt that.

Related

Parse XML data to JSON

In our environment we use MS SQL w/ stored procedures. In those procedures we return our results as XML and when access the data as we need to.
I'm introducing some charts into our tools which are 3rd party and require specific formats in order to operate and I am running into an issue.
In this screenshot, you are able to see what the structure should look like which I can get to work with the plugin just fine. The issue is with how SimpleXML handles single result sets.
As you can see in the image below, with one result item, it is no longer formatted as an array. The problem being is that the plugin expects to find the data in the format in the first example, but when there is only one value, it doesn't store it as an array.
As you can see from this image, the dataset for the escalationTypes is in the array format where the one below, submittedByDepartment is not.
I am trying to find out if there is something I can do to fix the root of this problem, with SimpleXML. Is this a common issue found with SimpleXML with a workaround?
UPDATE
Here is a sample of the XML Object I am working with: http://pastebin.com/uPh0m3qX
I'm not 100% clear what your required structure is, but in general, it's not a good idea to jump straight from XML to JSON or vice versa. Both can represent data in various ways, and what you really want is to extract data from one and turn it into the other.
Note that this is what SimpleXML is designed to help you with - it never contains any arrays, but it gives you an API which helps you extract the data you need.
If I understand correctly, you want to build an array from each of the dataset elements, and put those into your JSON, so you'd want something like this:
foreach ( $xml->children() as $item_name => $item ) {
foreach ( $item->dataset as $dataset ) {
$json[$item_name]['dataset'] = (array)$dataset->attributes();
}
}
Note that neither of those loops will behave differently if there is only one item to loop over. SimpleXML decides whether to behave like an array or an object based on how you use it, not based on what the XML looks like.
Note that while you can build a more general XML to array (or XML to JSON) function, getting it to always give the desired output from any input will probably take more time, and lead to harder-to-debug code, than writing specific code like the above.
you can declare the object as an array by adding (array) before referencing the variable. (array)$wasobject

Is there a way to query JSON in PHP?

I've used Google, Yahoo, AND Bing, but I can't find any good answers. I've seen jLinq, but I want to be able to query JSON in PHP in hopes of having a not an SQL database, but instead all data storage within the filesystem on my server. No, I don't care how bad it sounds.
Ideas nonetheless? I would think that there would be a PHP class on this.
-----EDIT-----
Guys, thanks for your answers so far, but I don't think that json_encode and json_decode are of much use. What I want to be able to do is encode/decode JSON, and be able to search it for specific keys with specific values. Albeit I have PROVEN to myself that I can do so, it's a lot of code for something that should be so simple. Anything else you have in mind?
You can use JsonQ package. This package can query over JSON data like Query Builder.
https://github.com/nahid/jsonq
You can call json_encode to convert your data to a string, and write this string to a file. Then when you want to use it, you read the entire file and call json_decode to convert it back to data. When you're done processing it, repeat the encode/write steps.
But if you have multiple processes doing this, they'll completely overwrite what each other is doing. So it's not a very good way to manage shared data.
You could try JSONPath it allows you to query json with xpath as you would xml.
Look into json_decode. This lets you take JSON as a string and parse it into an object in PHP. You could theoretically store the strings as files, and use file_get_contents to retrieve the string from the file.
You would have to write your own searching/indexing/updating/etc algorithms, but if you don't want to use a real database solution (since you said, No, I don't care how bad it sounds.), then I guess this would work.
To search for values in the object you get from json_decode, look into in_array and array_search

Return object instead of json_encode

So, I found that making my WebMethod As Object, Return Dictionary rather than As String, Return JavaScriptSerializer.Serialized() reduces the size of the JSON by ~ 20%.
Yeah, I know this isn't a big deal for traditional webapps where you're serving the consumer (in the past) and a few kb would be big, but it's HUGE for B2B where you're trying to serve up to your customers AJAXd jQuery pages with far less data transmission and greater speed when transmitting dynamic tables that could be potentially 100mb before dynamicization and id lists of about 1-2mb, but I digress.
It looks like json_encode does the same thing adding more than necessary to the JSON, from what I've read on other posts. Is there a way to simply output the array as an object or build an object from multiple arrays and export that?
1) Is print (and its' family) the only way to output?
2) Is json_encode (and its' family) necessary? After all, I don't have to decode if I output properly at the jQuery level.
I'm a big fan of speed & efficiency. As AJAX/jsLibs take over, and data becomes bigger while these hunkering server-side scripts go by the wayside, it looks like the next logical objective (aside from a standardized push to client) is to keep the size of the JSON as small as possible.
How can I keep the garbage with AJAX/PHP down to a mininum? How can I export arrays as object directly?
Thanks for bearing with me. I'm terrible with vocabulary. I hope what I want to do is relatively clear enough.
As always, thanks in advance, and thank you stack for being my brain!
The problem I was having with .net webmethod was that I was javascriptserializing my output before sending it out with <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> included. That's what added the extra data to my json output.
Arrays can be exported as is with json_encode, and that's all that's needed.

Which is better for parsing XML string in PHP? simplexml_load_string OR any xml_to_array converter function?

I want to parse large data from xml to array in PHP.
I have two option,
1st is using simplexml_load_string which will give me an object, from which I can make my desired object.
2nd is using any xml_to_array converter class/function which will give me an array, from which I can make my desired object.
Please guide me pros and cons of these methods. Which method I should go with?

qbasic version of PHP serialize/unserialize

I can't find this anywhere. I have some old basic programs I am working on (thanks to qb64 that came out, now they work on winxp - win7)
in order to serialize (like php) I need to know how this process works so that i can convert BASIC do it. it does not have to be fancy, but I would like to get an understanding how it works.
I like the way php does it, although since BASIC can not do 'associative" arrays, i would think it is much easier.
so in simple terms, is there a source for serialize/unserialize ?
looks like you'd serialize it with simple string concatenation. Use something like "||" as your seperator. Since there are no associative arrays, you don't have to worry about names, just value.
Then you'd use instr() and left$() or mid$() to split them back out.
For multidimensional arrays, it would be considerably more complex and I haven't given it the time to figure out exactly how I'd do it, but I thought about using seperatators like ||0|0|| for array(0,0) and ||0|1|| for array(0,1) or even ||0|1|1|| for array (0,1,1)

Categories