Simplexml从变量获取路径 [英] Simplexml get path from variable
问题描述
有没有一种方法可以将路径作为变量传递给simplexml节点? 这是我尝试过的:
Is there a way to pass the path to a simplexml node as a variable? This is what I tried:
//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 ,尤其是SimpleXML的 xpath()
方法.不用使用PHP的->
运算符进行遍历,而是使用XPath的/
运算符进行遍历,否则,可以完全实现所需的效果:
What you need is XPath, and more specifically SimpleXML's xpath()
method. Instead of traversing using PHP's ->
operator, you would traverse using XPath's /
operator, but otherwise, could achieve exactly the effect you wanted:
$comp = 'component[1]/structuredBody[1]/component';
echo count( $xml->xpath($comp) );
您可能会认为可以将其简化为'component/structuredBody/component'
,但是会找到与表达式匹配的所有可能路径-也就是说,如果有多个structuredBody
元素,它将搜索所有他们.这实际上可能有用,但它并不等同于$xml->component->structuredBody->component
,实际上是$xml->component[0]->structuredBody[0]->component
的简写.
You might think that this could be simplified to 'component/structuredBody/component'
, but that would find all possible paths matching the expression - that is if there are multiple structuredBody
elements, it will search all of them. That might actually be useful, but it is not equivalent to $xml->component->structuredBody->component
, which is actually shorthand for $xml->component[0]->structuredBody[0]->component
.
一些注意事项:
- 与大多数使用SimpleXML的操作不同,结果是一个数组,而不是另一个SimpleXML对象(将其视为一组搜索结果).因此,至关重要的是,在将元素0作为对象访问之前,请检查它是否为空.
- 您可以在上面的示例中看到,XPath从1开始计数,而不是从0开始计数.我不知道为什么,但是以前它使我陷入困境,所以我想警告您.
- SimpleXML库建立在仅支持XPath 1.0的基础上. 您在网上看到的有关XPath 2.0的示例可能无法正常工作.
- XPath 1.0没有默认名称空间"的概念,并且SimpleXML不会自动注册要在XPath中使用的名称空间前缀,因此,如果您使用的是名称空间,则需要使用
- Unlike most operations with SimpleXML, the result is an array, not another SimpleXML object (think of it as a set of search results). It is therefore vital that you check it is not empty before accessing element 0 as an object.
- As you can see in the example above, XPath counts from 1, not 0. I don't know why, but it's caught me out before, so I thought I'd warn you.
- The library SimpleXML is built on supports only XPath 1.0; examples you see online for XPath 2.0 may not work.
- XPath 1.0 has no notion of a "default namespace", and SimpleXML doesn't automatically register namespace prefixes for use in XPath, so if you're working with namespaces, you need to use
registerXPathNamespace()
.
这篇关于Simplexml从变量获取路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!