HTML DOM:如何在PHP中正确使用textContent属性

时间:2017-02-04 00:13:13

标签: php html dom

每当我尝试走到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; 
    }
}

1 个答案:

答案 0 :(得分:2)

您可以在DOM文档上使用XPathtext()返回所有文本节点。

$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);
}