DOMDocument in php
我刚刚开始阅读有关DOM的文档和示例,以便对文档进行爬网和解析。
例如,我有部分文档如下所示:
<div id="showContent">
<table>
<tr>
<td>
Crap
</td>
</tr>
<tr>
<td width="172" valign="top"><a href="link"><img height="91" border="0" width="172" class="" src="img"></a></td>
<td width="10"> </td>
<td valign="top"><table cellspacing="0" cellpadding="0" border="0">
<tbody><tr>
<td height="30"><a class="px11" href="link">title</a><a><br>
<span class="px10"></span>
</a></td>
</tr>
<tr>
<td><img height="1" width="580" src="crap"></td>
</tr>
<tr>
<td align="right">
<a href="link"><img height="16" border="0" width="65" src="/buy"></a>
</td>
</tr>
<tr>
<td valign="top" class="px10">
<p style="width: 500px;">description.</p>
</td>
</tr>
</tbody></table></td>
</tr>
<tr>
<td>
Crap
</td>
</tr>
<tr>
<td>
Crap
</td>
</tr>
</table>
</div>
我正在尝试使用以下代码来获取所有标记并分析其中是否存在废话或信息:tr
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('.//div[@id="showContent"]');
foreach ($tags as $tag) {
$string="";
$string=trim($tag->nodeValue);
if(strlen($string)>3) {
echo $string;
echo '<br>';
}
}
但是,我得到的只是没有标签的剥离字符串,例如:
Crap
Crap
Title
Description
但我想得到:
<tr>
<td>Crap</td>
</tr>
<tr>
<a href="link">title</a>
</tr>
如何保留html节点(标签)?