XML命名空间 - 如何获取它们?

时间:2016-07-31 04:29:59

标签: php xml xpath

尝试在其中提取带有名称空间的XML。我自己试图理解这一点;但我似乎无法确定我正在做什么的错误。

我将此设置为变量$myXMLData,并运行以下代码以吐出title属性:

$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>";
  }

但我的输出是空白的。我在这做错了什么?请帮忙......!

3 个答案:

答案 0 :(得分:2)

你确实在nopaste中注册了错误的命名空间。这是文档中的两个名称空间。

  • http://mws.amazonservices.com/schema/Products/2011-10-01
    没有前缀的元素
  • http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd
    前缀为ns2的元素

title使用前缀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>

答案 1 :(得分:0)

您是否已将标题设置为text/xml?默认情况下,PHP将Content-Type设置为text / html,因此浏览器会尝试将XML显示为HTML。这就是你可能得到空白结果的原因。

尝试添加此内容:

header('Content-Type: text/xml');

答案 2 :(得分:0)

// Register namespace, set in xml declaration
$sxe->registerXPathNamespace('ns2','http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd');
// And use the same prefix as in xml
$result=$sxe->xpath('//ns2:title'); 

<强> demo

或以这种方式

$ns = $sxe->getNamespaces(true);
$sxe->registerXPathNamespace('ns2',$ns['ns2']);
$result=$sxe->xpath('//ns2:title');

<强> demo