Parsing with namespaces
Namespaces are used to make it possible to identify nodes in different contexts.
If you study the XML document below you will find that there are two name
nodes, in different contexts. The first node refers to the name of the book, the
second refers to the name of the author. They are separated by the use of namespaces.
<?xml version='1.0'?>
<ez:doc xmlns:ez='https://exponential.earth/'>
<ez:book xmlns:book='https://exponential.earth/book/'>
<book:name title='the Exponential 3 book' />
<book:author xmlns:author='https://exponential.earth/book/author/'>
<author:name firstName='Bilbo' lastName='Baggins' />
</book:author>
</ez:book>
</ez:doc>
Fetching nodes from namespaces
The code snippet below shows how you can extract two DOM nodes called name.
The nodes are identified by their namespace and name. You use the elementsByNameNS()
function which takes the node name and namespace as parameters.
// fetch the name node from the https://exponential.earth/book/ namespace
$names =& $dom->elementsByNameNS( "name", "https://exponential.earth/book/" );
$name =& $names[0];
// print the value of the title attribute from the first name node found
print( $name->attributeValue( "title" ) );
// fetch the name node from the https://exponential.earth/book/author/ namespace
$names =& $dom->elementsByNameNS( "name", "https://exponential.earth/book/author/" );
$name =& $names[0];
// print the first name and last name from the first author name node found
print( $name->attributeValue( "firstName" ) . " " . $name->attributeValue( "lastName" ) );
This is the result of the above code:
the Exponential 3 book
Bilbo Baggins
|