根据属性查找特定元素

mse*_*ole 5 php xml xpath

我一直在回顾所有旧代码并尝试优化它.我最近偶然发现的事情让我感到困惑的是试图为此找到一个xpath解决方案:

function findit($search) {
    $i=0;
    foreach($xml as $page) { //loop to find specific $element based on $attribute
       if($page['src']==$search) { return $i; }
       $i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

需要返回,$i以便以后可以用它来引用XML中的元素.

看起来它应该是可能的,而且我发现了一些似乎应该工作的xpath字符串,但却没有.它们通常preceding-children通过xpath()函数引用和计算它们,但我找不到原始的源代码,也不知道如何将它转换为PHP xpath字符串.

这甚至可能吗?或者它比我已经获得的更好/更快/更有效率?建议/解决方案?

编辑:对于Tandu的解决方案

我的XML文件示例

<range>
    <page src="attribute1" />
    <page src="attribute2" />
    etc...
    <page src="attribut20" />
</range>
Run Code Online (Sandbox Code Playgroud)

在我当前的PHP函数中,$i总是返回0但应返回$search找到的任何位置.编辑,所以它不再需要转换simplexml.

function findit($search) {
    $dom=new DOMDocument('1.0');
    $dom->load($file);
    $xpath=new DOMXPath($dom);
    $i=$xpath->evaluate("count(/range/page[@src='$search']/preceding-sibling::*)");
    die($dom->saveXML());
}
Run Code Online (Sandbox Code Playgroud)

Exp*_*lls 3

PHP 至少有两种(据我所知)处理 Xpath 的方法:DOMXPath库(与DOMDocument一起使用)和SimpleXML(它有自己的xpath()方法)。如果您想计算实际表达式(例如在示例中获取 i ,则必须使用DOMXPath::evaluate(). SimpleXML::xpath()只会返回一个节点列表(就像 一样。php 中DOMXPath::query()也有xpath_方法,但这些似乎是其他方法的功能版本,并且仍然需要 DOM 上下文节点对象。

我不确定xml上面的示例中的 是什么,但下面的示例使用 DOMXPath。据我所知,没有简单的方法可以转换SimpleXMLDOMDocument. 您只需单独加载 xml 即可。

$xml = <<<XML
   <root>
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="two" />
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="one" />
      <child attribute="one" />
   </root>
XML;
$dom = new DOMDocument;
$dom->loadXML($xml);
//DOMXPath requires DOMDocument in its constructor
$xpath = new DOMXPath($dom);
//evaluate will return types .. we are expecting an int, not a DOMNodeList
//Look for a child node of root named "child" with attribute="two"
//Count all its preceding siblings.
$i = $xpath->evaluate('count(/root/child[@attribute="two"]/preceding-sibling::*)');
Run Code Online (Sandbox Code Playgroud)