Using PHP DOM document, to select HTML element by its class and get its text

前端 未结 2 1048
太阳男子
太阳男子 2020-12-13 15:50

I trying to get text from div where class = \'review-text\', by using PHP\'s DOM element with following HTML (same structure) and following code.

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 16:10

    Expanding on Frak Houweling answer, it is also possible to use DomXpath to search within a specific DomNode. This can be acheived by passing the contextNode as a second argument to DomXpath->query method:

    $dom = new DOMDocument;
    $dom->loadHTML ($html);
    $xpath = new DOMXPath ($dom);
    
    foreach ($xpath->query ("//section[@class='page single-review']") as $section)
    {
        // search for sub nodes inside each element
        foreach ($xpath->query (".//div[@class='review-text']", $section) as $review)
        {
            echo $review->nodeValue;
        }
    }
    

    Note that when searching inside nodes you need to use relative paths by adding a dot . at the beginning of the expression:

    "//div[@class='review-text']" // absolute path, search starts from the root element
    ".//div[@class='review-text']" // relative path, search starts from the provided contextNode
    

提交回复
热议问题