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

前端 未结 2 1046
太阳男子
太阳男子 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:03

    The following XPath query does what you want. Just replace the argument provided to $xpath->query with the following:

    //div[@class="review-text"]
    

    Edit: For easy development, you can test your own XPath query's online at http://www.xpathtester.com/test.

    Edit2: Tested this code; it worked perfectly.

    
            
    Outstanding ...
    '; $classname = 'review-text'; $dom = new DOMDocument; $dom->loadHTML($html); $xpath = new DOMXPath($dom); $results = $xpath->query("//*[@class='" . $classname . "']"); if ($results->length > 0) { echo $review = $results->item(0)->nodeValue; } ?>

提交回复
热议问题