如何使用xpath仅显示某些值

时间:2016-03-07 23:43:43

标签: php xml xpath

<root>
    <a>
         <b>
              <c>cat</c>
              <d>dog</d>
              <e>elephant</e>
         </b>
    </a>
    <a>
         <b>
              <c>bat</c>
              <d>koala</d>
              <e>iguana</e>
         </b>
    </a>
</root>

$query = "//a/b/c[contains('cat', .)]";

foreach ($entries as $entry) {
    //Trying to echo cat and the <d> tag here
    //Expected output "cat" and "dog" only (if possible to make dog as a variable)

}

使用xpath查找关键字。我使用查询变量从XML文件中查找包含单词“cat”的信息。

  1. 我现在有关于如何在foreach函数中显示cat节点的问题。它找到了猫,但它没有显示猫数据
  2. 我如何显示里面的其他音符,例如使用查询查找“cat”,我如何显示“dog”。这同样适用于蝙蝠,如果我把关键字蝙蝠,我怎么显示考拉。
  3. 感谢

2 个答案:

答案 0 :(得分:0)

还有其他方法可以做到这一点 - 但这是一种适合你的方式(将在文本中显示'cat'的所有兄弟姐妹):

<?php
  $xml = simplexml_load_file("test.xml");

  $catParent = $xml->xpath("a/b/c[contains(., 'cat')]/..")[0];

  foreach($catParent as $child){
    echo $child."<br>";
  }
?>

或者,如果你只想展示'猫':

<?php
  $xml = simplexml_load_file("test.xml");

  $catText = (string)$xml->xpath("a/b/c[contains(., 'cat')]")[0];

  echo $catText;
?>

答案 1 :(得分:0)

您使用此xpath查询来获取所需的子节点:

$query = "//a/b/c[contains('cat', .)]";

然后,要获取/回显其值和所有兄弟值,您可以使用以下代码:

foreach( $xml->xpath( $query ) as $node )
{
    echo $node->asXML() . PHP_EOL;
    echo $node->__toString() . PHP_EOL;

    foreach( $node->xpath('preceding-sibling::* | following-sibling::*') as $sibling )
    {
        echo $sibling->asXML() . PHP_EOL;
        echo $sibling->__toString() . PHP_EOL;
    }
}
  • ->asXML()获取完整的XML节点
  • ->__toString()以文本形式获取节点(顺便说一下,您可以只使用echo $node;
  • xpath子查询preceding-sibling::* | following-sibling::*获取所有前面/后面的节点兄弟。

如果您只想获得<e>兄弟,请将以上xpath子查询替换为:

preceding-sibling::e | following-sibling::e

或 - 如果您对返回'cat'不感兴趣 - 直接使用此xpath查询:

echo $xml->xpath( "//a/b/c[contains('cat', .)]/../e" )[0]->__toString();
// output: elephant