|
/Coding/php:
XML to Object Conversion
In working with the KnowledgeTree API[2] I found that the response to my http posts to the API came back in the form of XML. I needed to get that XML into PHP-processable form, and a quite a bit of googling mostly turned up home-grown solutions, a lot of them referring to themselves as "xmltoarray" functions . Until I found the PHP-native solution, SimpleXMLElement[1]. Hopefully this post will help to push SimpleXMLElement a little higher in Google's search listings....
Suppose I have a big junk of XML in string form, such as this response to a KnowledgeTree API directory listing:
0 − 1 Root Folder / −− - −
2 F n/a n/a DroppedDocuments n/a DroppedDocuments n/a Administrator n/a n/a n/a n/a n/a n/a n/a n/a RWA n/a n/a folder folder Folder n/a - −
11 F n/a n/a Public n/a Public n/a Administrator n/a n/a n/a n/a n/a n/a n/a n/a RWA n/a n/a folder folder Folder n/a
in a variable called $response. Converting to a structured object is simply:
$xml = new SimpleXMLElement($response);
And then the object might be processed as follows:
if( $xml->status_code != 0 ){ echo 'Error - operation failed: ' . $xml->message; } else { // print_r($xml); // to see data structure echo " folder ID = " . $xml->results->folder_id . "
"; echo "folder name = " . $xml->results->folder_name . "
"; echo "folder path = " . $xml->results->full_path . ""; foreach ($xml->results->items->item as $value) { echo "item type = " . $value->item_type . " "; echo "item ID = " . $value->id . " "; echo "item name = " . $value->filename . "
"; } }
[1] http://php.net/manual/en/book.simplexml.php
[2] http://wiki.knowledgetree.com/REST_Web_Service
posted at: 05:27 | path: /Coding/php | permanent link to this entry