Parse XML data to JSON - php

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

Related

Convert xml to MAP in php using simplexml, NOT json

I'm trying to figure out how to take a simple custom xml file (its actually an EML file, but simpeXML works with it anyway) and take tagnames and the text that follows (i think simpleXML calls them children) and put them into a MAP, with key/value pairs. I've looked at some examples on this site and others about converting to arrays and such but they all seem extremely complicated for my needs. I should note that my custom xml does not contain ANY attributes and this conversion only needs to work with MY custom xml file and not any others ever.
So a simple example of my eml file is here
<lesson>
<unit>4</unit>
</lesson>
So then basically what I would want is a MAP, or whatever a key/value collection is called in php that would give me:
Map[0](lesson,null)
Map[1](unit,4)
It's important that I get the null values (or an empty string is ok too), so I can verify that the eml file is valid. I need to validate it with php, not using a namespace validator or a dtd file or however that is done. So the first key/value pair, or the root tag, HAS to be lesson, and then ill also verify that there is a unit tag, then a title tag, then at least one other type of tag etc...I can do that easy if i can get everything into a key/value collection. Also, there are many tagnames that are the same, so keys should be not-unique. However for the value, they should be unique, but only to the tag name. So unit can only one one "4", but another tag, lets say imageID could also have "4". This is not a requirement but a "nice to have" and I can probably figure that out if its not simple. But if its REALLY hard then I will skip it all together.
I hope this makes sense.
And no, I don't think Im allowed to use json. I'm sure it can be done in simpleXMl but if its impossible, then please provide a method to do it in json (assuming that json is included with PHP and not an extension that has to be loaded).
This is university homework, so I can't use extensions or anything else that would require anything beyond what comes with the XAMPP basic package (php, mysql, apache etc...).
Really surprised I got no votes or views or answers or anything on this. I did figure this out in the end. Oh yeah...got the tumbleweed badge for this too!
Anyway the answer was actually quite simple. I used the simplexml_load_file function in PHP which actually supports any kind of xml-style. So after running this,
$eml = simplexml_load_file("unit.eml");
I then did things like this
foreach ($eml->children() as $child)
$tag = $child->getName();
$tagInfo = $child;
And used $tag and $tagInfo to iterate through my eml and get everything I needed.

Building a multidimensional JSON array through PHP/MySQL

I am trying to build what I think is a multidimensional array in json through php and a connection to a mysql database.
Here's the output I am looking for:
[{"region":"Americas"},
{"region":"West","division":"Americas","revenues":"100000","headcount":"6"},
{"region":"East","division":"Americas","revenues":"1500000","headcount":"8"},
{"region":"South","division":"Americas","revenues":"1000000","headcount":"7"},
{"office":"San Francisco","location":"50 Kearny Street", "branch":"West"},
{"office":"Los Angeles","location":"200 Sepulveda","branch":"West"},
{"office":"New York","location":"Penn Street","branch":"East"},
{"office":"Philadelphia","location":"155 Trent","branch":"East"},
{"office":"New Jersey","location":"420 Broadway","branch":"East"},
{"office":"Atlanta","location":"39000 Parker","branch":"South"}]
This gives me the feed into a graphing program that creates the proper visualization. My database returns all the values in the JSON above (region, division, revenues, etc.) EXCEPT for "branch" which I had to hand code myself. I can't sure "region" again (because of the graphing algorithm) so I had to rename it to "branch." Under this current configuration, the "Americas" is the top node, with the "regions" underneath, and then the "branches" under each region as appropriate.
So far, I've only been able to build a basic JSON array using PHP and the json_(encode) function ; to get the output above, I edited the file by hand to make sure it would render properly in my graph, which it does.
The question I am looking to answer is: what is the fastest and easiest way to build the above array on the fly? Through a loop in PHP, I would imagine, but I can't get my head around what that would look like.
I probably left out information you need to help, so this is just to get the ball rolling.
Thanks!
Look at this topic: Looping a multidimensional array in php
You can loop through the array using the foreach construct

What is the best way to find a specified element using PHP's SimpleXMLElement class?

The project that I'm currently working on involves translating a website that was written in Python to PHP code. The part I'm doing now requires me to send $_GET requests to a web server. The response that I get back is always in XML format, so I'm using the *simplexml_load_file()* function to fetch the result.
I need to parse through the XML that the web server sends back to me. Python had a nice library called BeautifulStoneSoup, which had a find() method that returned the contents of a specified attribute.
After looking at the list of PHP functions at http://php.net/manual/en/book.simplexml.php, I cannot seem to find anything that allows me to specify an attribute name and get the contents. Keep in mind that attribute I may be looking for is not necessarily going to always be one level deep into the XML array. It may be several dimensions into the array.
I can provide an example if this wasn't specific enough. Thanks for the help, friends!
Xpath sounds like what your looking for. It allows for searches to be made within any level of an XML directory.
The following example looks multiple levels deep with an xml directory and checks if the description node contains whatever is held within $txtSearch
$holidayDoc = simplexml_load_file($url);
$qry = "//channel/item[description[contains(text(),\"$txtSearch\")]]";
$holidayDoc->xpath($qry);
Results can then be iterated through using a foreach loop
You can run an XPath query:
$xml->xpath('//#myattribute')

jQuery $.post PHP whats the best way to handle a multidimensional object or array

Ok, I usually do this in reverse, post a specific data set, then expect an JSON object back, however. In today's case I kinda need to the opposite. Except my confusion is brought on by there is no static elements to work with. My data won't be coming from a customary form, so serialization is not an option I don't think. So before I go more into it a little info on the spec
I have a Unordered list that can have anywhere from 1 List Element to dozens, each one contains 3 pieces if info I need to pass in a POST to my PHP as I would a form. But Im not sure whats the best way to handle it.
Can I pass it as an array through the post where the array is what it is? Or do I have to transform the output to resemble a JSON object and post that, treating it as a JSON object with the PHP and running it through json_decode? Not sure what to do here, so any advice is greatly appreciated.
edit worth mentioning is I can get the data I need from the list elements, its just what should I do with it to pass it in a post, so that it posts in sense like its a multidimensional object or array
You can pass the array from js using ajax as array. And it will come to $_POST as array without any additional steps
You need to transform it into a JSON string and then json_decode it on the other side. This is where node.js can be superior as a backend because you can pass the array directly to Node without going into and out of JSON.

Why need to use JSON in php and AJAX

I just started doing jQuery last week, and so far I already made some basic systems with ajax, like basic jQuery CRUD and simple chat system without referencing on other's work for I decided to test myself on how far I can do systems alone in jQuery(without JSON and XML yet).
But when I decided to look at other's work (hoping to get/learn good practices and codes out there) many or almost every program that deals with ajax have some JSON in it. So I decided to study and read JSON specially this one, but I guess because it's my first time dealing with it, I'm having a problem sinking it into my brain. Yeah I know it is a "lightweight way of describing hierarchical data", I also know how to make JSON like mixing a literal array and object in JS, and how to dsplay it in js.
But my question is, what's the difference and what's the advantage than not using it?
When I can still get and store data on the server using ajax and database without JSON.
By the way I haven't focus on XML yet because based from my research it's better to use JSON in AJAX.
Can you give me some actual scenario dealing with
s1. ajax php mysql (this with what disadvantages?)
and
s2. ajax php mysql json (this with what advantages?)
I mean, my focus is to send and get data, and I already can do it with s1.
Sorry if you find my question stupid. Tia. :)
Why use JSON? The answer is portability and structure.
JSON is portable because parsers and writers are available for many, many languages. This means that JSON that a PHP script generates can be very easily understood by a JavaScript script. It is the best way to transmit complex structures like arrays and objects, and have it still be compatible with multiple languages.
JSON provides structure because the data you transmit with it can have consistent formatting. This is instead of transmitting back plain-text (i.e. unformatted) data, like comma-separated or delimited data.
Data that is merely delimited (for example, "BookName1,BookName2,BookName3") is more difficult for humans to understand, debug, and work with. If you wanted to debug a response between your server and your browser and the data was delimited (like my example above), you might have a hard time understanding it. Also, if you want to add different data types, provide separate records, etc., then your custom data format becomes more complicated. Eventually, you might end up reinventing JSON.
As a side note, JSON is indeed better than XML. It is much more efficient space-wise. There are no tag names to take up space. Structure is created via nested braces, instead of verbose tags.
Resources
Here is an interesting article on the differences and pros/cons of XML and JSON: http://www.json.org/xml.html
Examples
Per your request, here is an example of encoding JSON with PHP. This is ripped from the docs:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Contrast this to something like this, without JSON:
a,1
b,2
c,3
d,4
e,5
To parse that, you'd have to iterate through each line, split the values yourself, and then create the array. This isn't that difficult, but imagine you have a nested object:
$arr = array ('a'=> array(1,2,3),'b'=> array('a' => 1, 'b' => 2),'c'=>3,'d'=> array(1,2,3,4,5) ,'e'=>5); // etc.
With JSON, it's no different to encode it. Just use json_encode. But, encoding this manually, and then decoding it manually would be significantly more work.
Programming in any sort of programming language, you have several different types of data at your disposal, including the very useful array type.
Interchanging data between Javascript and any server side language can only happen through strings. I.e. you can send and return any text, but there's no way to send a native array or number type.
JSON is an elegant way to express array and other types using only a string. This way you can pass arbitrary data back and forth between different environments and are not limited to pure text. XML solves the same kind of problem, but is often overkill for simple AJAX requests.

Categories