gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:10:03 26 4
gpt4 key购买 nike

我试图通过使用具有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com