php xpath: query within a query result

前端 未结 2 1703
终归单人心
终归单人心 2021-02-10 11:20

I\'m trying to parse an html file.

The idea is to fetch the span\'s with title and desc classes and to fetch their information in each div that

相关标签:
2条回答
  • 2021-02-10 11:55

    Make the queries relative... start them with a dot (e.g. ".//…").

    foreach ($arts as $art) {
        // Note: single slash (direct child)
        $titles = $xpath->query("./span[@class='title']", $art);
        if ($titles->length > 0) {
            $title = $titles->item(0)->nodeValue;
            echo $title;
        }
    
        $descs = $xpath->query("./span[@class='desc']", $art);
        if ($descs->length > 0) {
            $desc = $descs->item(0)->nodeValue;
            echo $desc;
        }
    }
    
    0 讨论(0)
  • 2021-02-10 12:01

    Instead of doing the second query try textContent

    foreach ($arts as $art) {
        echo $art->textContent;
    }
    

    textContent returns the text content of this node and its descendants.

    As an alternative, change the XPath to

    $expression="//div[@class='thebest']/span[@class='title' or @class='desc']";
    $arts = $xpath->query($expression);
    
    foreach ($arts as $art) {
        echo $art->nodeValue;
    }
    

    That would fetch the span children of the divs with a class thebest having a class of title or desc.

    0 讨论(0)
提交回复
热议问题