DOM: fetch all text nodes in the document (PHP)

為{幸葍}努か 提交于 2019-12-18 06:53:58

问题


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

Thanks.


回答1:


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

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


来源:https://stackoverflow.com/questions/768737/dom-fetch-all-text-nodes-in-the-document-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!