Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through elements in DOMNodeList?

Tags:

dom

loops

php

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?

like image 710
Colm Mulhall Avatar asked Nov 29 '13 12:11

Colm Mulhall


1 Answers

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])');
like image 60
ThW Avatar answered Sep 21 '22 14:09

ThW