I am trying to query an XML document that uses namespaces. I have had success with xpath without namespaces, but no results with namespaces. This is a basic example of what I was trying. I have condensed it slightly, so there may be small issues in my sample that may detract from my actual problem.
Sample XML:
<?xml version="1.0"?>
<sf:page>
<sf:section>
<sf:layout>
<sf:p>My Content</sf:p>
</sf:layout>
</sf:section>
</sf:page>
Sample PHP Code:
<?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 is that "p" is a "DOMNodeList Object ( )" and it's length is 0. Any help would be appreciated.
DOMDocument constructor does not take the contents, but version and encoding. Instead of:
$path = "index.xml";
$content = file_get_contents($path);
$dom = new DOMDocument($content);
Try this:
$path = "index.xml";
$doc = new DOMDocument();
$doc->load($path);
You must define 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>
精彩评论