我有以下 (PHP) 代码,它遍历整个 DOM 文档以获取所有文本节点。这是一个有点丑陋的解决方案,我相信一定有更好的方法……那么,有吗?
$skip = false;
$node = $document;
$nodes = array();
while ($node) {
if ($node->nodeType == 3) {
$nodes[] = $node;
}
if (!$skip && $node->firstChild) {
$node = $node->firstChild;
} elseif ($node->nextSibling) {
$node = $node->nextSibling;
$skip = false;
} else {
$node = $node->parentNode;
$skip = true;
}
}
谢谢。
最佳答案
您需要的 XPath 表达式是 //text()
。尝试将其与 DOMXPath::query
一起使用.例如:
$xpath = new DOMXPath($doc);
$textnodes = $xpath->query('//text()');
关于php - DOM:获取文档中的所有文本节点 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/768737/