1
这是我的代码:如何获取HTML文档的文本节点总数?
我想要得到HTML文档中文本节点的总数。
// a new dom object
$dom = new domDocument;
// load the html into the object
$dom->loadHTMLFile('translated/test.html');
// discard white space
$dom->preserveWhiteSpace = false;
$i = 0;
// get elements by tagname body
while ($bodynodes = $dom->getElementsByTagName('body')->item($i)) {
myFunc($bodynodes);
$i++;
}
//var_dump($holder);
function myFunc($node) {
static $i;
if (!isset($i)) {
$i = 0;
}
if ($node->childNodes) {
foreach ($node->childNodes as $subNode):
myFunc($subNode);
endforeach;
}else {
if ($node->nodeType == 3 && trim($node->nodeValue) != ''):
$i++;
endif;
}
if ($node->lastChild):
echo $i;
endif;
}
但我得到的是
Result ====> 1233
,因为只有我的HTML文档中的文本3段。
$ node-> type == 3表示只允许文本节点,并且我也有空白节点的筛选器,anywayx我可以应用更多的筛选器(如果需要的话),但问题是如何才能获得计数只返回一次价值? – atif