XPath PHP - 检查父类中是否存在类

时间:2015-09-06 16:36:04

标签: php html xpath

我有这种HTML文件:

<div class="find-this">I do not need this</div>

<div class="content ">
    <div class="find-this">
          <span class="yellowcard"></span>
          <span class="name">Cristiano Ronaldo</span>
    </div>
</div>
<div class=" content">
    <div class="find-this">
        <span class="redcard"></span>
        <span class="name">Lionel Messi</span>
    </div>
</div>

到目前为止,我得到了find-this父类中的content类。

$nodes = $xpath->query("//div[contains(@class,'content')]//div[@class='find-this']");
foreach ($nodes as $key => $node) {
        echo "Player ". $key .": " . $node->nodeValue;
    }

结果:

Player0: Cristiano Ronaldo
Player1: Lionel Messi

如何找出哪个find-this类是<span class="yellowcard">的父级,哪一个是<span class="redcard">的父级? 谢谢你的建议。

1 个答案:

答案 0 :(得分:1)

要选择find-this的父div <span class="yellowcard">div的父<span class="redcard">,请使用下面显示的XPath:

$yellow_nodes = $xpath->query("//span[@class='yellowcard']/parent::div[@class='find-this']");
$red_nodes = $xpath->query("//span[@class='redcard']/parent::div[@class='find-this']");