Use SimpleXML's xpath() method:
- <?php
- $xmlData =<<< END
- <?xml version="1.0"?>
- <data>
- <item>
- <id>20</id>
- <name>mangoes</name>
- <price>11</price>
- </item>
- <item>
- <id>22</id>
- <name>strawberries</name>
- <price>5</price>
- </item>
- <item>
- <id>23</id>
- <name>grapes</name>
- <price>25</price>
- </item>
- </data>
- END;
- // read XML data
- $xml = simplexml_load_string($xmlData)↩
- or die("ERROR: Cannot create SimpleXML object");
- // create a custom collection of <name> nodes
- // using an XPath query
- // result: "mangoes strawberries grapes "
- foreach ($xml->xpath('//name') as $name) {
- echo "$name ";
- }
Comments
XPath provides a standard addressing mechanism for an XML document, making it easy to access and manipulate every element, attribute, and text node on the XML document tree.
SimpleXML supports building custom node collections via its xpath() method. This method accepts an XPath location path (either absolute or relative) and selects all the nodes matching that path. In this example, the //name shortcut selects <name> elements anywhere below the document element and returns them as a node collection that can be processed in a loop.
Tip | For a friendly introduction to XPath, visit http://www.melonfire.com/community/columns/trog/article.php?id=83. |