note 92135 added to function.simplexml-element-registerXPathNamespace

From: Date: Fri, 10 Jul 2009 12:06:56 +0000
Subject: note 92135 added to function.simplexml-element-registerXPathNamespace
Groups: php.notes 
Request: Send a blank email to php-notes+get-158144@lists.php.net to get a copy of this message
A problem occurs when the XML document you want to parse does not declare a namespace consistently; sometimes it does declare the namespace, sometimes not. Your XPath queries will fail if you use the ns prefix in your query while it is not declared in the XML (resulting in this error: "SimpleXMLElement::xpath() [simplexmlelement.xpath]: Undefined namespace prefix"). On the other hand the query will also fail if you don't use the prefix if the namespace is declared in the XML (will return an empty result). Since you can only register a namespace prefix for XPath if the namespace is declared (registerXPathNamespace()), the only way to cope with this, is to write the prefix in your XPath queries with a little variable. eg. <?php // get used namespaces $namespaces = $this->simple_xml->getNamespaces(TRUE); // say namespace 'pre:' is not defined consistently // define namespace prefix var for xpath queries $this->ce_prefix = isset($namespaces['pre']) ? 'pre:' : ''; // your xpath queries look like this (section/pre:value or section/value) $res = $this->simple_xml->xpath('section/'. $this->ce_prefix .'value'); ?> It is not an elegant solution but it I couldn't find a better one. (Add a registerNamespace($prefix, $url) method? ;)) ---- Server IP: 91.199.167.18 Probable Submitter: 94.208.69.164 ---- Manual Page -- http://www.php.net/manual/en/function.simplexml-element-registerXPathNamespace.php Edit -- https://master.php.net/note/edit/92135 Del: integrated -- https://master.php.net/note/delete/92135/integrated Del: useless -- https://master.php.net/note/delete/92135/useless Del: bad code -- https://master.php.net/note/delete/92135/bad+code Del: spam -- https://master.php.net/note/delete/92135/spam Del: non-english -- https://master.php.net/note/delete/92135/non-english Del: in docs -- https://master.php.net/note/delete/92135/in+docs Del: other reasons-- https://master.php.net/note/delete/92135 Reject -- https://master.php.net/note/reject/92135 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158144) next »