note 124578 added to class.domxpath

From: Date: Wed, 08 Jan 2020 09:16:27 +0000
Subject: note 124578 added to class.domxpath
Groups: php.notes 
Request: Send a blank email to php-notes+get-213809@lists.php.net to get a copy of this message
When working with XML (as a strict format) might be very important to give a namespace to XPath object in order to make it work properly. I was experiencing "query" always returning empty node lists, it could not find anything. Only a broad "//*" was able to show off only the root element. Then found out that registering the namespace reported in the "xmlns" attribute of the root element in the XPath object, and writing the namespace near the elements name, made it work properly. So for an XML like this (from a sitemap): ``` <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://example.com/index.php</loc> <lastmod>2005-01-01</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> </urlset> ``` I needed the following XPath configuration: <?php $doc = new DOMDocument; $doc->load("sitemap.xml"); $xpath = new DOMXPath($doc); $xpath->registerNamespace('ns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); $nodes = $xpath->query('//ns:urlset/ns:url'); ?> Then again, that "xmlns" could be provided dynamically from the root element attribute of course. ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.168 (proxied: 79.30.69.221) ---- Manual Page -- http://php.net/manual/en/class.domxpath.php Edit -- https://master.php.net/note/edit/124578 Del: integrated -- https://master.php.net/note/delete/124578/integrated Del: useless -- https://master.php.net/note/delete/124578/useless Del: bad code -- https://master.php.net/note/delete/124578/bad+code Del: spam -- https://master.php.net/note/delete/124578/spam Del: non-english -- https://master.php.net/note/delete/124578/non-english Del: in docs -- https://master.php.net/note/delete/124578/in+docs Del: other reasons-- https://master.php.net/note/delete/124578 Reject -- https://master.php.net/note/reject/124578 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#213809) next »