note 87141 added to function.simplexml-element-xpath
| From: | michael dot mauch at gmx dot de | Date: | Thu, 20 Nov 2008 22:46:20 +0000 |
| Subject: | note 87141 added to function.simplexml-element-xpath | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-146783@lists.php.net to get a copy of this message | ||
Matt's comment is rather helpful, but that problem is not a fault of PHP, but a general problem
with XPath and default namespaces. See e.g. http://www.edankert.com/defaultnamespaces.html
and http://plasmasturm.org/log/259/ .
If your XML doc has a default namespace (xmlns="some_namespace") and you want to use
xpath, you have to register a prefix for the default namespace and use that prefix in all of your
xpath expressions.
<?php
$xml_doc = <<<XML
<?xml version='1.0'?>
<!-- without namespace: -->
<!-- <document> -->
<!-- with default namespace: -->
<document xmlns="uri:some_namespace">
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what's the question?
</body>
</document>
XML;
$xml = simplexml_load_string($xml_doc);
$namespaces = $xml->getNamespaces(true);
if(isset($namespaces[""])) // if you have a default namespace
{
// register a prefix for that default namespace:
$xml->registerXPathNamespace("default", $namespaces[""]);
// and use that prefix in all of your xpath expressions:
$xpath_to_document = "//default:document";
}
else
$xpath_to_document = "//document";
$document = $xml->xpath($xpath_to_document);
print_r($document);
?>
----
Server IP: 212.124.37.9
Probable Submitter: 80.136.66.107
----
Manual Page -- http://www.php.net/manual/en/function.simplexml-element-xpath.php
Edit -- https://master.php.net/note/edit/87141
Del: integrated -- https://master.php.net/note/delete/87141/integrated
Del: useless -- https://master.php.net/note/delete/87141/useless
Del: bad code -- https://master.php.net/note/delete/87141/bad+code
Del: spam -- https://master.php.net/note/delete/87141/spam
Del: non-english -- https://master.php.net/note/delete/87141/non-english
Del: in docs -- https://master.php.net/note/delete/87141/in+docs
Del: other reasons-- https://master.php.net/note/delete/87141
Reject -- https://master.php.net/note/reject/87141
Search -- https://master.php.net/manage/user-notes.php