Simplexml 从变量获取路径

Simplexml get path from variable

有没有办法将路径作为变量传递给 simplexml 节点? 这是我试过的:

//set the path to the node in a variable
$comp = 'component->structuredBody->component';

echo count($xml->component->structuredBody->component); //=== 13
echo count($xml->$comp); //===0
echo count($xml->{$comp});//===0

你需要的是XPath, and more specifically SimpleXML's xpath() method。您可以使用 XPath 的 / 运算符遍历,而不是使用 PHP 的 -> 运算符进行遍历,否则,可以完全达到您想要的效果:

$comp = 'component[1]/structuredBody[1]/component';
echo count( $xml->xpath($comp) );

您可能认为这可以简化为 'component/structuredBody/component',但那样会找到 所有匹配表达式 的可能路径 - 即如果有多个 structuredBody 元素,它将搜索所有这些元素。这实际上可能有用,但它不等同于 $xml->component->structuredBody->component,后者实际上是 shorthand for $xml->component[0]->structuredBody[0]->component.

注意几点:

  • 与 SimpleXML 的大多数操作不同,结果是一个数组,而不是另一个 SimpleXML 对象(将其视为一组搜索结果)。因此,在将元素 0 作为对象访问之前,检查它是否为空至关重要。
  • 正如您在上面的示例中看到的那样,XPath 从 1 开始计数,而不是 0。我不知道为什么,但我之前就被它抓住了,所以我想我应该警告你。
  • 构建 SimpleXML 的库仅支持 XPath 1.0; 您在网上看到的 XPath 2.0 示例可能不起作用。
  • XPath 1.0 没有 "default namespace" 的概念,并且 SimpleXML 不会自动注册用于 XPath 的名称空间前缀,因此如果您使用名称空间,则需要使用 registerXPathNamespace() .