每当我尝试走到HTML文件的DOM(我只对文本元素感兴趣)时,如果我指向节点的textContent属性,它将回显所有的文本那个特定的节点树。 例如:
<html lang="en">
<body>
<p> 1st text I need</p>
<a href="#">2nd text I need</a>
<table>
<tr>
<td>3rd text I need</td>
</tr>
</table>
</body>
</html>
结果如下:
#document
html
html 1st text I need 2nd text I need 3rd text I need
body 1st text I need 2nd text I need 3rd text I need
p 1st text I need
a 2nd text I need
table 3rd text I need
tr 3rd text I need
td 3rd text I need
我想从具有直接文字内容的元素中提取仅文本。在上面的示例中,它们将是 p , a 和 td 。
我该怎么做?
以下是代码(摘自here):
<?php
$doc = new DOMDocument();
@$doc->loadHTMLFile('test.html');
walkDom($doc);
function walkDom($node, $level = 0)
{
$indent = '';
for ($i = 0; $i < $level; $i++)
$indent .= ' '; //prettifying the output
if($node->nodeType != XML_TEXT_NODE) {
echo $indent .'<b>' . $node->nodeName .'</b>';
if( $node->nodeType == XML_ELEMENT_NODE ) {
echo $node->textContent;
}
echo '<br>';
}
$cNodes = $node->childNodes;
if (count($cNodes) > 0)
{
$level++; // go one level deeper
foreach($cNodes as $cNode)
walkDom($cNode, $level);
$level = $level - 1;
}
}
答案 0 :(得分:2)
您可以在DOM文档上使用XPath。 text()
返回所有文本节点。
$doc = new DOMDocument;
$doc->loadhtml('<html lang="en">
<body>
<p> 1st text I need</p>
<a href="#">2nd text I need</a>
<table>
<tr>
<td>3rd text I need</td>
</tr>
</table>
</body>
</html>');
$doc->normalizeDocument();
$xpath = new DOMXpath($doc);
$results = $xpath->query("//text()");
foreach($results as $node) {
echo trim($node->wholeText);
}