DOM:获取文档中的所有文本节点(PHP) [英] DOM: fetch all text nodes in the document (PHP)

查看:81
本文介绍了DOM:获取文档中的所有文本节点(PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(PHP)代码遍历整个DOM文档以获取所有文本节点。这是一个很丑的解决方案,我确定必须有一个更好的方法...所以,是吗?

I've have the following (PHP) code that traverses an entire DOM document to get all of the text nodes. It's a bit of a ugly solution, and I'm sure there must be a better way... so, is there?

$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 。例如:

The XPath expression you need is //text(). Try using it with DOMXPath::query. For example:

$xpath = new DOMXPath($doc);
$textnodes = $xpath->query('//text()');

这篇关于DOM:获取文档中的所有文本节点(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆