-1

I want to select children of the current div node and save them into variable:

<div id="summary">
<p>aaaaaaa</p>
<p>bbbbbbb</p>
<br>
<p>ccccccc</p>
<a></a>
<p>ddddddd</p>
</div>

I tried

$summary = $dom->saveHTML($xpath->query('//div[@id="summary"]/child::*')->item(0));

But it only returns the first P tag which is very strange to me cause '*' is supposed to get all of the children, so where I can fix it to select all of the children instead of only the first one?

user7031
  • 435
  • 4
  • 16

1 Answers1

1

The two culprits are saveHTML and "->item(0)". The query returns an array of values, and you can access each element through a foreach loop.

<?php
$content = 
'<div id="summary">
<p>aaaaaaa</p>
<p>bbbbbbb</p>
<p>ccccccc</p>
<a></a>
<p>ddddddd</p>
</div>';
$xml = new SimpleXMLElement($content);


$entries =  $xml->xpath('//div[@id="summary"]/child::*');
foreach ($entries as $entry) {
    echo $entry;
}
?>

I removed the break for a well-formed example. In the above code, $entries contains an array of all the appropriate values (aaaaaaa through ddddddd). "item(0)" accesses the first element of the array. Your Xpath is correct, but use of those two functions are wrong. The question is, are you looking to assign to a variable, or serialize the result?

saveHTML dumps the document you created using "createElement" into a string. Saving the information in a variable is really simple as assigning to it.

  • I thought child statement will return all the children as a whole, and it was wrong, is there any method that can return the children as a whole unit instead of an nodelist? – user7031 Aug 07 '15 at 16:03
  • In other words, would like to preserve the tag, other metadata, and value around the children as a while instead of just grabbing the value? If so, you would be looking into a _Regular Expression tool_ like preg_match(), instead of Xpath queries. – ExternCowWindows Aug 07 '15 at 16:27