我在迭代DOMNodeList中的元素时遇到了问题.我试图将整个段落放入一个字符串.我可以用这个分别得到每个句子:
$node = $paragraph->item(0); //first line of the paragraph
$node = $paragraph->item(1); //second line of the paragraph
Run Code Online (Sandbox Code Playgroud)
但我似乎无法遍历所有句子并将它们放入一个字符串中.我试过这个,但它不起作用:
for($i=0; $i<3; $i++)
{
$node = $paragraph->item($i);
}
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以做到这一点?
ThW*_*ThW 18
DOMNodeList实现Traversable,只需使用foreach()
foreach($nodeList as $node) {
//...
}
Run Code Online (Sandbox Code Playgroud)
当然也有可能.
$length = $nodeList->length;
for ($i = 0; $i < $length; $i++) {
$node = $nodeList->item($i);
//...
}
Run Code Online (Sandbox Code Playgroud)
要获取节点内的所有文本内容,可以使用$ nodeValue或$ textContent属性:
$text = '';
foreach($nodeList as $node) {
$text .= $node->textContent;
}
Run Code Online (Sandbox Code Playgroud)
但这是针对节点列表的.你说这是段落的文字内容.如果您将段落作为DOMElement对象,它也具有$ nodeValue和$ textContent属性.
$text = $paragraphNode->textContent;
Run Code Online (Sandbox Code Playgroud)
如果您通过Xpath获取节点,DOMXpath :: evaluate()可以将文本内容作为字符串返回.
$xpath = new DOMXpath($dom);
$text = $xpath->evaluate('string(//p[1])');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8538 次 |
| 最近记录: |