Abh*_*ani 14 html php domdocument
我试图通过使用PHP的DOM元素和下面的HTML(相同的结构)和下面的代码来从div中获取文本,其中class = 'review-text'.
然而,这似乎不起作用
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>
';
Run Code Online (Sandbox Code Playgroud)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;
}
Run Code Online (Sandbox Code Playgroud)此博客提供了按类选择元素的XPATH语法
我在StackOverflow,在线教程中尝试过很多例子,但似乎都没有.我错过了什么吗?
Fra*_*ing 26
以下XPath查询执行您想要的操作.只需用以下代码替换提供给$ xpath-> query的参数:
//div[@class="review-text"]
Run Code Online (Sandbox Code Playgroud)
编辑:为了便于开发,您可以在http://www.xpathtester.com/test上在线测试自己的XPath查询.
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;
}
?>
Run Code Online (Sandbox Code Playgroud)
扩展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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在节点内部搜索时,您需要通过.在表达式开头添加一个点来使用相对路径:
"//div[@class='review-text']" // absolute path, search starts from the root element
".//div[@class='review-text']" // relative path, search starts from the provided contextNode
Run Code Online (Sandbox Code Playgroud)