PHP simplexml:为什么xpath停止工作? [英] PHP simplexml: why does xpath stop working?

查看:73
本文介绍了PHP simplexml:为什么xpath停止工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在供应商稍微更改了XML标头之后,发生了一件奇怪的事情.我曾经能够使用xpath读取内容,但是现在我什至无法获得回复

A strange thing happened after a supplier changed the XML header a bit. I used to be able to read stuff using xpath, but now I can't even get a reply with

$xml->xpath('/');

他们对此进行了更改...

They changed it from this...

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE NewsML SYSTEM "http://www.newsml.org/dl.php?fn=NewsML/1.2/specification/NewsML_1.2.dtd" [
<!ENTITY % nitf SYSTEM "http://www.nitf.org/IPTC/NITF/3.4/specification/dtd/nitf-3-4.dtd">
%nitf;
]>
<NewsML>
...

对此:

<?xml version="1.0" encoding="iso-8859-1"?>
<NewsML
  xmlns="http://iptc.org/std/NewsML/2003-10-10/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://iptc.org/std/NewsML/2003-10-10/ http://www.iptc.org/std/NewsML/1.2/specification/NewsML_1.2.xsd http://iptc.org/std/NITF/2006-10-18/   http://contentdienst.pressetext.com/misc/nitf-3-4.xsd"
>
...

推荐答案

最可能的原因是因为他们在文档中引入了默认名称空间(xmlns="http://iptc.org/std/NewsML/2003-10-10/").简单地说,SimpleXML对默认名称空间的支持不是很好.

Most likely this is because they've introduced a default namespace (xmlns="http://iptc.org/std/NewsML/2003-10-10/") into their document. SimpleXML's support for default namespaces is not very good, to put it mildly.

您可以尝试显式注册名称空间前缀吗?

Can you try to explicitly register a namespace prefix:

$xml->registerXPathNamespace("n", "http://iptc.org/std/NewsML/2003-10-10/");
$xml->xpath('/n:NewsML');

您必须调整XPath表达式以在 every 元素上使用"n:"前缀.这是一些其他信息: http://people.ischool.berkeley.edu/~felix/xml/php-and-xmlns.html .

You would have to adapt your XPath expressions to use the "n:" prefix on every element. Here is some additional info: http://people.ischool.berkeley.edu/~felix/xml/php-and-xmlns.html.

根据规范:

registerXPathNamespace()函数创建一个前缀/ns上下文用于下一个XPath查询.

The registerXPathNamespace() function creates a prefix/ns context for the next XPath query.

这意味着必须在每个XPath查询之前调用它,因此包装XPath查询的函数是很自然的事情:

This means it would have to be called before every XPath query, thus a function to wrap XPath queries would be the natural thing to do:

function simplexml_xpath_ns($element, $xpath, $xmlns)
{
    foreach ($xmlns as $prefix_uri)
    {
        list($prefix, $uri) = explode("=", $prefix_uri, 2);
        $element->registerXPathNamespace($prefix, $uri);
    }
    return $element->xpath($xpath);
}

用法:

$xmlns = ["n=http://iptc.org/std/NewsML/2003-10-10/"];
$result = simplexml_xpath_ns($xml, '/n:NewsML', $xmlns);

这篇关于PHP simplexml:为什么xpath停止工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆