PHP Function Reference

PHP SimpleXMLElement - registerXPathNamespace() Method



The PHP SimpleXMLElement::registerXPathNamespace() method creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

Syntax

public SimpleXMLElement::registerXPathNamespace(prefix, namespace)

Parameters

prefix Required. Specify the namespace prefix to use in the XPath query for the namespace given in namespace.
namespace Required. Specify the namespace to use for the XPath query. It must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

Return Value

Returns true on success or false on failure.

Example: setting a namespace prefix to use in an XPath query

The example below shows the usage of SimpleXMLElement::registerXPathNamespace() method.

<?php
$xmlstr = <<<XML
<book xmlns:chap="https://example.com/chapter-title">
  <title>My Book</title>
  <chapter id="1">
    <chap:title>Chapter 1</chap:title>
    <para>This is chapter 1 content.</para>
  </chapter>

  <chapter id="2">
    <chap:title>Chapter 2</chap:title>
    <para>This is chapter 2 content.</para>
  </chapter>
</book> 
XML;

$xml = new SimpleXMLElement($xmlstr);

$xml->registerXPathNamespace('d', 'https://example.com/chapter-title');
$result = $xml->xpath('//d:title');

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

The output of the above code will be:

Chapter 1
Chapter 2

Please note that, how the XML document shown in the example above sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of d 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() method avoids future modification of the query even if the provider changes the namespace prefix.


❮ PHP SimpleXML Reference