How do you request namespaces with PHP / XPath / DOM

I am trying to query an XML document that uses namespaces. I had success with xpath without namespaces, but there were no results with namespaces. This is a basic example of what I tried. I squeezed it a bit, so there may be small problems in my sample that can distract me from my real problem.

XML example:

<?xml version="1.0"?> <sf:page> <sf:section> <sf:layout> <sf:p>My Content</sf:p> </sf:layout> </sf:section> </sf:page> 

PHP code example:

 <?php $path = "index.xml"; $content = file_get_contents($path); $dom = new DOMDocument($content); $xpath = new DOMXPath($dom); $xpath->registerNamespace('sf', "http://developer.apple.com/namespaces/sf"); $p = $xpath->query("//sf:p", $dom); 

My result: "p" is a "DOMNodeList Object ()", and the length is 0. Any help would be appreciated.

+4
source share
2 answers

The DOMDocument constructor does not accept content, but a version and an encoding. Instead:

 $path = "index.xml"; $content = file_get_contents($path); $dom = new DOMDocument($content); 

Try the following:

 $path = "index.xml"; $doc = new DOMDocument(); $doc->load($path); 
+1
source

You must define the namespace in your XML file:

 <?xml version="1.0"?> <root xmlns:sf="http://developer.apple.com/namespaces/sf"> <sf:page> <sf:section> <sf:layout> <sf:p>My Content</sf:p> </sf:layout> </sf:section> </sf:page> </root> 
0
source

Source: https://habr.com/ru/post/1308762/


All Articles