使用XPath时获取孙子nodeValue

时间:2016-01-31 13:57:07

标签: php curl xpath domdocument

我正在寻找一种方法来检索孙子的nodeValue。我只能明确地访问"我对这个班级有明确的访问权限。课程如下图所示。我该怎么做?

<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)

1 个答案:

答案 0 :(得分:1)

您可以通过传递&#39;祖父&#39;来进行相对XPath查询。 $rating作为上下文元素:

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