PHP Tutorial - PHP registerXPathNamespace() Function






The registerXPathNamespace() function creates a namespace context for the next XPath query.

Syntax

PHP registerXPathNamespace() Function has the following syntax.

registerXPathNamespace(prefix,ns);

Parameter

ParameterIs RequiredDescription
prefixRequired.Namespace prefix to use in the XPath query for the namespace given in ns
nsRequired.Namespace to use for the XPath query

Return

Returns TRUE on success. FALSE on failure

Example

Create a namespace context for the next XPath query:


<?php/*w w  w.  j  ava 2 s  . c om*/
$xml=<<<XML
<book xmlns:chap="http://example.org/chapter-title">
  <title>My Book</title>
  <chapter id="1">
    <chap:title>Chapter 1</chap:title>
    <para>PHP Data Types</para>
  </chapter>
  <chapter id="2">
    <chap:title>Chapter 2</chap:title>
    <para>PHP Statements</para>
  </chapter>
</book>
XML;

$sxe=new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('c','http://example.org/chapter-title');
$result=$sxe->xpath('//c:title');
foreach ($result as $title){
  echo $title . "\n";
}
?>

The code above generates the following result.