I am having a problem iterating through elements in a DOMNodeList. I am trying to put a whole paragraph into a string. I can get each sentence separately using this:
$node = $paragraph->item(0); //first line of the paragraph
$node = $paragraph->item(1); //second line of the paragraph
But I cannot seem to loop through all of the sentences and put them into the one string. I have tried this but it didn't work:
for($i=0; $i<3; $i++)
{
$node = $paragraph->item($i);
}
Any ideas how I could do this?
DOMNodeList implements Traversable, just use foreach()
foreach($nodeList as $node) {
//...
}
Of course a for is possible, too.
$length = $nodeList->length;
for ($i = 0; $i < $length; $i++) {
$node = $nodeList->item($i);
//...
}
To get all the text content inside a node, the $nodeValue or $textContent properties can be used:
$text = '';
foreach($nodeList as $node) {
$text .= $node->textContent;
}
But this is for a node list. You said that this is the text content of a paragraph. If you have the paragraph as an DOMElement object, it has $nodeValue and $textContent properties as well.
$text = $paragraphNode->textContent;
And if you fetched the nodes via Xpath, DOMXpath::evaluate() can return the text content as a string.
$xpath = new DOMXpath($dom);
$text = $xpath->evaluate('string(//p[1])');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With