使用 XPath 时获取孙子节点值

get the grandson nodeValue when using XPath

我正在寻找一种方法来检索孙子的节点值。我只能明确访问 "I have unambiguous access to this class" class ,如下所示。我该怎么做?

<class="I have unambiguous access to this class">
- <class="childClass">
-- <class="grandsonClass">

///////

function curlGet($url){
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($url));

    $results = curl_exec($ch);

    curl_close($ch);
    return $results;
}


function returnXPathObject($item){
    $xmlPageDom = new DOMDocument();
    @$xmlPageDom->loadHTML($item);
    $xmlPageXPath = new DOMXPath($xmlPageDom);
    return $xmlPageXPath;
}

$examplePage = curlGet("www.example.com");
$exampleXPath = returnXPathObject($examplePage);

$rating = $exampleXPath->query("//span[@class='grandfather']"); // I can access this guy, but I want it's grandchild.

// get child of grandfather's child (grandson of grandfather)

您可以通过将 'grandfather' $rating 作为上下文元素传递来进行相对 XPath 查询:

$query = "./span[@class='childClass']/span[@class='grandsonClass']";
$grandSon = $exampleXPath->query($query, $rating);