简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM