我想获取 <p>
之间的所有文本和<h3>
以下 HTML 的标记
<div class="bodyText">
<p>
<div class="articleBox articleSmallHorizontal channel-32333770 articleBoxBordered alignRight">
<div class="one">
<a href="url" class="img"><img src="url" alt="bar" class="img" width="80" height="60" /></a>
</div>
<div class="two">
<h4 class="preTitle">QIEZ-Lieblinge</h4>
<h3 class="title"><a href="url" title="ABC" onclick="cmsTracking.trackClickOut({element:this, channel : 32333770, channelname : 'top_listen', content : 14832081, callTemplate : '_htmltagging.Text', action : 'click', mouseevent : event});">
Prominente Gastronomen </a></h3>
<span class="postTitle"></span>
<span class="district"><a href="http://www.qiez.de/berlin/top-listen" title="TOP-LISTEN in Berlin">Berlin</a></span> </div>
<div class="clear"></div>
</div>
I want this TEXT</p>
<h3>I want this TEXT</h3>
<p>I want this TEXT</p>
<p>
<div class="inlineImage alignLeft">
<div class="medium">
<img src="http://images03.qiez.de/Restaurant+%C3%96_QIEZ.jpg/280x210/0/167.231.886/167.231.798" width="280" height="210" alt="Schöne Lage: das Restaurant Ø. (c)QIEZ"/>
<span class="caption">
Schöne Lage: das Restaurant Ø. (c)QIEZ </span>
</div>
</div>I want this TEXT</p>
<p>I want this TEXT</p>
<p>I want this TEXT<br /> </p>
<blockquote><img src="url" alt="" width="68" height="68" />
"Eigentlich nur drei Worte: Ich komme wieder."<span class="author">Tina Gerstung</span></blockquote>
<div class="clear"></div>
</div>
我想要所有“我想要这个文本”。我使用了xpath查询
//div[contains(@class,'bodyText')]/*[local-name()='p' or local-name()='h3']
但它没有给我文本 if <p>
标签后跟任何其他标签
最佳答案
看起来您的 p 元素中包含有 div 元素,该元素无效并且会弄乱事情。如果您在循环中使用 var_dump,您可以看到它确实获取了节点,但 nodeValue 为空。
对 html 的一个快速而肮脏的修复是将 p 元素中包含的第一个 div 包装在一个 span 中。
<span><div class="articleBox articleSmallHorizontal channel-32333770 articleBoxBordered alignRight">...</div></span>
更好的解决方法是将 div 元素放在段落之外。
如果您使用肮脏的解决方法,您将需要像这样更改查询:
$xpath->query("//div[contains(@class,'bodyText')]/*[local-name()='p' or local-name()='h3']/text()");
如果您无法控制源 html。您可以复制 html 并删除有问题的 div:
$nodes = $xpath->query("//div[contains(@class,'articleBox')]");
$node = $nodes->item(0);
$node->parentNode->removeChild($node);
使用 simple_html_dom 可能会更容易。也许你可以尝试这个:
include('simple_html_dom.php');
$dom = new simple_html_dom();
$dom->load($html);
foreach($dom->find("div[class=bodyText]") as $parent) {
foreach($parent->children() as $child) {
if ($child->tag == 'p' || $child->tag == 'h3') {
// remove the inner text of divs contained within a p element
foreach($dom->find('div') as $e)
$e->innertext = '';
echo $child->plaintext . '<br>';
}
}
}
关于php - 如果 p 标签后面跟着任何其他标签,xpath 不会返回文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25279258/