Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : SimpleXML functions : SimpleXMLElement->registerXPathNamespace()

SimpleXMLElement->registerXPathNamespace()

Creates a prefix/ns context for the next XPath query ()

Example 2259. Setting a namespace prefix to use in an XPath query

<?php

$xml
= <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
   <title>My Book</title>
   <chapter id="1">
       <chap:title>Chapter 1</chap:title>
       <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
           In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
           Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
           ultricies id, mauris.</para>
   </chapter>
   <chapter id="2">
       <chap:title>Chapter 2</chap:title>
       <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
           gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
           vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
           tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
   </chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach (
$result as $title) {
 echo
$title . "\n";
}

?>

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.


Related Examples ( Source code ) » simplexml element registerxpathnamespace






Change Language


Follow Navioo On Twitter
SimpleXMLElement->addAttribute()
SimpleXMLElement->addChild()
SimpleXMLElement->asXML()
SimpleXMLElement->attributes()
SimpleXMLElement->children()
SimpleXMLElement->__construct()
SimpleXMLElement->getDocNamespaces()
SimpleXMLElement->getName()
SimpleXMLElement->getNamespaces()
SimpleXMLElement->registerXPathNamespace()
SimpleXMLElement->xpath()
simplexml_import_dom
simplexml_load_file
simplexml_load_string
eXTReMe Tracker