I have a xml file structured like
<?xml version="1.0"?> <library> <book id="1003"> <title>Jquery MVC</title> <author>Me</author> <price>500</price> </book> <book id="1001"> <title>Php</title> <author>Me</author> <price>600</price> </book> <book id="1002"> <title>Where to use IFrame</title> <author>Me</author> <price>300</price> </book> </library>
In order to sort this xml according to the book id,
after reviewing this method from stackoverflow
i coded like this
$dom = new DOMDocument();
$dom->load('DOM.xml');
$library = $dom->documentElement;
$xpath = new DOMXPath($dom);
$result = $xpath->query('/library/book');
function sort_trees($t1,$t2){
return strcmp($t1['id'], $t2['id']);
}
usort($result, 'sort_trees');
print_r($result);*/
But it gives me an error
Warning: usort() expects parameter 1 to be array, object given in /var/www/html/testphp/phpxml/readxml.php on line 24
The answer you cite is for SimpleXML, but you are using DOMDocument.
If you want to continue to use DOMDocument you need to keep its API in mind.
If you need to create a new output document with the nodes sorted, create a new document, import the root element, then import the book nodes in sorted order and add to the document.
However, a much better approach is to use XSLT:
Then use XSLTProcessor (or
xsltprocfrom the command line):