Find only those nodes belonging to a particular namespace.
Use SimpleXML's children() method with the namespace URI (Universal Resource Identifier):
- <?php
- // define XML data string
- // containing namespaces
- $xmlData = <<< END
- <?xml version="1.0"?>
- <data xmlns:home="http://www.some.domain/xmlns/home" ↩
- xmlns:work="http://www.some.domain/xmlns/work">
- <home:file>music.txt</home:file>
- <work:file>accounts.dat</work:file>
- <work:file>inbox.mbx</work:file>
- <home:file>expenses.xls</home:file>
- <home:file>addressbook.doc</home:file>
- </data>
- END;
- // read XML data
- $xml = simplexml_load_string($xmlData);
- // process nodes in "work" namespace
- // result: "accounts.dat inbox.mbx "
- foreach ($xml->children("http://www.some.domain/xmlns/work") as $file)
- {
- echo "$file ";
- }
- ?>
Comments
It's easy to isolate only those child nodes belonging to a particular namespace if you're using SimpleXML: just pass the namespace URI to the children() method as an additional argument. In this example, this technique has been used to isolate all the nodes in the "work" namespace under the document element. The resulting node collection can then be processed in the usual manner, with a foreach() or other loop.