使用PHP DOM文档,通过其类选择HTML元素并获取其文本
发布时间:2020-05-25 09:46:00 所属栏目:PHP 来源:互联网
导读:我试图从div中获取文本,其中class =’review-text’,通过使用具有以下 HTML(相同结构)的 PHP的DOM元素和以下代码. 但是这似乎不起作用 HTML $html = div class=page-wrapper section class=page single-review itemtype=http://schema.o
|
我试图从div中获取文本,其中class =’review-text’,通过使用具有以下 HTML(相同结构)的 PHP的DOM元素和以下代码. 但是这似乎不起作用 > 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>
';
> 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->查询的参数替换为以下内容://div[@class="review-text"] 编辑: EDIT2: <?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;
}
?> (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
