note 103461 modified in domxpath.query by danbrown
| From: | danbrown@php.net | Date: | Thu, 14 Apr 2011 14:57:23 +0000 |
| Subject: | note 103461 modified in domxpath.query by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178834@lists.php.net to get a copy of this message | ||
To help with the problem where the default namespace is not registered with the DOMXPath object, you
can use the following replacement to update your paths accordingly:
<?php
$xml = <<<EOS
<root xmlns="urn:test">
<foo>bar</foo>
</root>
EOS;
$expression = '//foo';
$prefix = 'fakeprefix';
$doc = new DOMDocument();
$doc->loadXML($xml);
$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);
// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
$xpath->registerNamespace($prefix, $context->namespaceURI);
$expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '$1' .
$prefix . ':$2', $expression);
var_dump($expression); // string(16) "//fakeprefix:foo"
}
$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"
?>
--was--
To help with the problem identified below where the default namespace is not registered with the
DOMXPath object, you can use the following replacement to update your paths accordingly:
<?php
$xml = <<<EOS
<root xmlns="urn:test">
<foo>bar</foo>
</root>
EOS;
$expression = '//foo';
$prefix = 'fakeprefix';
$doc = new DOMDocument();
$doc->loadXML($xml);
$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);
// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
$xpath->registerNamespace($prefix, $context->namespaceURI);
$expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '$1' .
$prefix . ':$2', $expression);
var_dump($expression); // string(16) "//fakeprefix:foo"
}
$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"
?>
http://php.net/manual/en/domxpath.query.php