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