一直在尝试提取一些带有 namespace 的 XML。我自己也尝试去理解这一点;但我似乎无法准确地确定我正在做的事情出了什么问题。
我将其设置为变量$myXMLData
,并运行以下代码来吐出标题属性:
$myXMLData=<<<XML
<getmatchingproductresponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<getmatchingproductresult asin="055726328X" status="Success">
<product>
<attributesets>
<ns2:itemattributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
<ns2:studio>lulu.com</ns2:studio>
<ns2:title>You Are a Spiritual Healer</ns2:title>
</ns2:itemattributes>
</attributesets>
<relationships>
</relationships>
</product>
</getmatchingproductresult>
<responsemetadata>
<requestid>4304bf06-acd2-4792-804a-394a2e01656f</requestid>
</responsemetadata>
</getmatchingproductresponse>
XML;
$sxe=new SimpleXMLElement($myXMLData);
$sxe->registerXPathNamespace('ns','http://mws.amazonservices.com/schema/Products/2011-10-01');
$result=$sxe->xpath('//ns:title');
foreach ($result as $title)
{
echo $title . "<br>";
}
但是我的输出是空白的。我在这里做错了什么?请帮忙...!
最佳答案
您确实在 nopaste 中注册了错误的命名空间。这是文档中的两个命名空间。
http://mws.amazonservices.com/schema/Products/2011-10-01
没有前缀的元素http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd
带有前缀 ns2 的元素
标题
使用前缀ns2
。您不必注册文档中使用的前缀。您可以而且应该只注册您自己的。在 SimpleXML 中,您必须对任何您想要调用方法 xpath() 的元素执行此操作。它有助于为其创建一个小功能。
$xmlns = [
'p' => 'http://mws.amazonservices.com/schema/Products/2011-10-01',
'pd' => 'http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd'
];
function registerNamespacesOnElement(
SimpleXMLElement $element, array $namespaces
) {
foreach ($namespaces as $prefix => $namespace) {
$element->registerXpathNamespace($prefix, $namespace);
}
}
$sxe=new SimpleXMLElement($xml);
registerNamespacesOnElement($sxe, $xmlns);
$result=$sxe->xpath('//pd:title');
foreach ($result as $title) {
echo $title . "<br>\n";
}
输出:
You Are a Spiritual Healer<br>
关于php - XML 命名空间 - 如何获取它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680748/