note 129327 added to domxpath.query

From: Date: Mon, 11 Mar 2024 20:07:51 +0000
Subject: note 129327 added to domxpath.query
Groups: php.notes 
Request: Send a blank email to php-notes+get-221242@lists.php.net to get a copy of this message
DOMXPath::query() doesn't support elements without a namespace very well. To use xpath with such elements, tell xpath about the document's namespace, like this: <?php $document = new DOMDocument(); $document->loadXML(<<<XML <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <stuff xmlns="http://example.com/schemas/stuff"> <thing color="red">This thing is red</thing> <thing color="green">This thing is green</thing> </stuff> XML) ?: throw new Exception(); $xpath = new DOMXPath($document); // normally, you'd expect to be able to this, but no: echo $xpath->query('thing[@color="green"]')->item(0)->textContent; $rootNode = $document->firstChild ?? throw new Exception(); $namespace = $rootNode->getAttribute("xmlns"); $xpath->registerNamespace("def", $namespace); // set the "def" namespace to the anonymous namespace of the document unset($rootNode, $namespace); // now you can xpath query the document as expected: echo $xpath->query('def:thing[@color="green"]')->item(0)->textContent; ?> > Warning: Attempt to read property "textContent" on null. > This thing is green ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.13.131 (proxied: 204.112.96.198) ---- Manual Page -- https://php.net/manual/en/domxpath.query.php Edit -- https://main.php.net/note/edit/129327 Del: integrated -- https://main.php.net/note/delete/129327/integrated Del: useless -- https://main.php.net/note/delete/129327/useless Del: bad code -- https://main.php.net/note/delete/129327/bad+code Del: spam -- https://main.php.net/note/delete/129327/spam Del: non-english -- https://main.php.net/note/delete/129327/non-english Del: in docs -- https://main.php.net/note/delete/129327/in+docs Del: other reasons-- https://main.php.net/note/delete/129327 Reject -- https://main.php.net/note/reject/129327 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221242) next »