使用PHP DOM文档,按类选择HTML元素并获取其文本


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

我试图通过使用带有以下HTML(相同结构)和以下代码的PHP的DOM元素,从div中获取文本,其中class='review-text'

但是这似乎不起作用

  1. HTML

    $html = '
        <div class="page-wrapper">
            <section class="page single-review" itemtype="http://schema.org/Review" itemscope="" itemprop="review">
                <article class="review clearfix">
                    <div class="review-content">
                        <div class="review-text" itemprop="reviewBody">
                        Outstanding ... 
                        </div>
                    </div>
                </article>
            </section>
        </div>
    ';
    
  2. PHP代码

        $classname = 'review-text';
        $dom = new DOMDocument;
        $dom->loadHTML($html);
        $xpath     = new DOMXPath($dom);
        $results = $xpath->query("//*[@class and contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
        if ($results->length > 0) {
            echo $review = $results->item(0)->nodeValue;
        }
    

按类选择元素的XPATH语法在本博客中提供

我尝试过许多来自StackOverflow的在线教程示例,但似乎都不起作用。我是不是错过了什么?

下面的XPath查询可以满足您的需要。只需将提供给$xpath->query的参数替换为以下内容:

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

编辑:为了便于开发,您可以在线测试自己的XPath查询,网址为http://www.xpathtester.com/test.

第2版:对该代码进行了测试;它运行得很好。

<?php
$html = '
    <div class="page-wrapper">
        <section class="page single-review" itemtype="http://schema.org/Review" itemscope="" itemprop="review">
            <article class="review clearfix">
                <div class="review-content">
                    <div class="review-text" itemprop="reviewBody">
                    Outstanding ... 
                    </div>
                </div>
            </article>
        </section>
    </div>
';
$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;
}
?>

扩展Frak Houweling答案,也可以使用DomXpath在特定的DomNode中搜索。这可以通过将contextNode作为第二个参数传递给DomXpath->query方法来实现:

$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;
    }
}

请注意,在节点内部搜索时,您需要通过在表达式开头添加一个点.来使用相对路径:

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