PHP - XML: Filtering XML Nodes by Namespace



PHP XML Tips - Part 11: Do you want to find only those nodes belonging to a particular namespace? You can look solution like this:
<?php
$xmlString = <<< END
<?xml version="1.0"?>
<data xmlns:home="http://www.mysite.com/xmlns/home" xmlns:pdf="http://www.mysite.com/xmlns/work">
  <home:file>content1.doc</home:file>
  <pdf:file>content2.pdf</pdf:file>
  <pdf:file>content3.pdf</pdf:file>  
  <home:file>content4.txt</home:file>
  <home:file>content5.rtf</home:file>
  <pdf:file>content6.pdf</pdf:file>        
</data>
END;

$xml  = simplexml_load_string($xmlString);

foreach($xml->children("http://www.mysite.com/xmlns/work") as $file){
  echo $file ." <br />";
}
?>

Result like this:

content2.pdf
content3.pdf
content6.pdf 


Series this article:
PHP - XML: Read from String
PHP - XML: Read from a File
PHP - XML: Retrieving Node Values
PHP - XML: Retrieving Attribute Values
PHP - XML: Processing XML
PHP - XML: Creating XML Document
PHP - XML: Adding XML Nodes
PHP - XML: Removing Node
PHP - XML: Replacing Node
PHP - XML: Filtering XML Nodes with XPath
PHP - XML: Filtering XML Nodes by Namespace


Tag: xml, node, namespace Category: PHP Basic Post : March 23rd 2008 Read: 3,047 Bookmark and Share

blog comments powered by Disqus