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

标签 php html domdocument

我试图通过使用具有以下 HTML(相同结构)和以下代码的 PHP 的 DOM 元素,从 div where 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;
        }
    

Blog 提供了按类选择元素的 XPATH 语法

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

最佳答案

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

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

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

编辑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;
}

?>

关于php - 使用 PHP DOM 文档,按类选择 HTML 元素并获取其文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182857/

相关文章:

Cakephp 类 'DOMDocument' 未找到

Java:如何加速给定 w3c dom 文档的 xpath 字符串生成?

javascript - 为什么我在这里得到的 document.getElementById 为 null?

php - 有人可以解释这 2 个引用用法在 PHP 中的区别吗?

html - 窗口水平收缩时,如何防止水平列表项垂直折叠?

html - 如何为输入中显示的文本创建偏移量?

PHP : Must login twice until session variables are set

php - 登录Symfony2后运行控制台命令后台

php - 调用未定义的方法 mysqli_stmt::get_result

javascript - 来自 html/javascript/php 中的 json 响应的折线图