xml xpath traversal using simplexml php extension
SimpleXMLElement::xpath — Runs XPath query on XML data and returns an array of SimpleXMLElement objects or FALSE in case of an error. The SimpleXML php extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.
We use simplexml to load the xml file as follows.
1 2 3 4 5 6 7 8 | <?php <?php $xml = simplexml_load_file("mysample.xml"); $books = $xml->xpath("/library/book/title"); foreach($books AS $book) { echo "$book<br />"; } ?> |
The input sample.xml is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <library> <book> <title>A</title> <author gender="female">B</author> <description>C</description> </book> <book> <title>C</title> <author gender="male">D</author> <description>E</description> </book> <book> <title>F</title> <author gender="male">G</author> <description>H</description> </book> </library> |
