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.
Access
public
Parameters
Parameter |
Type |
Required |
Description |
---|---|---|---|
|
Required |
The namespace prefix to use in the XPath query for the namespace given in |
|
|
Required |
The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using |
Returns
Type |
Description |
---|---|
Returns |
Examples
Setting a namespace prefix to use in an XPath query
$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"; }Result:
Chapter 1 Chapter 2