在DOMNodeList中迭代元素时遇到问题。我正试图把一整段文字编成一个字符串。我可以用分别得到每一句话
$node = $paragraph->item(0); //first line of the paragraph
$node = $paragraph->item(1); //second line of the paragraph
但我似乎无法循环浏览所有的句子并将它们放在一个字符串中。我试过了,但没用:
for($i=0; $i<3; $i++)
{
$node = $paragraph->item($i);
}
你知道我该怎么做吗?
DOMNodeList实现Traversable,只需使用foreach()
foreach($nodeList as $node) {
//...
}
当然,for也是可能的。
$length = $nodeList->length;
for ($i = 0; $i < $length; $i++) {
$node = $nodeList->item($i);
//...
}
要获取节点内的所有文本内容,可以使用$nodeValue或$textContent属性:
$text = '';
foreach($nodeList as $node) {
$text .= $node->textContent;
}
但这是一个节点列表。你说这是一段文字的内容。如果您将段落作为DOMElement对象,那么它也具有$nodeValue和$textContent属性。
$text = $paragraphNode->textContent;
如果您通过Xpath获取节点,则DOMXpath::evaluate()可以将文本内容作为字符串返回。
$xpath = new DOMXpath($dom);
$text = $xpath->evaluate('string(//p[1])');
我发现使用foreach()
在适度大的DOMNodeList上迭代非常慢。一个更快的方法是在do-while
循环中使用DOMNode $nextSibling
属性,如下所示:
$el = $paragraph->firstChild;
do {
// do stuff
} while ($el = $el->nextSibling);
在php.net上的一条评论中也提到了这一点。