Brian Bruman Brian Bruman - 1 month ago 8
PHP Question

GetElementsByTagName only returning first node in array

I am trying to get each element in the array using

getElementsByTagName


$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
<order>
<line-items type="array">
<line-item>
<title>Title 1</title>
</line-item>
<line-item>
<title>Title 2</title>
</line-item>
</line-items>
</order>';


But have only been able to get the first result (Title 1).

$dom = new DomDocument();
$dom->loadXML($xmlString);
$order = $dom->getElementsByTagName('line-items');

foreach($order as $get){
echo $dom->getElementsByTagName('title')->item(0)->textContent;
}


How do I ensure I loop over
line-items
and get every possible iteration of
title
in every
line-item
?

Answer

You need to iterate through all the 'line-item' elements and get the title, not 'line-items' as it just appeared once. So the modified code might look like below :

$order = $dom->getElementsByTagName('line-item');
foreach($order as $get){
   //echo $dom->getElementsByTagName('title')->item(0)->textContent;
   //echo $order->getElementsByTagName('title')->item(0)->textContent;

     echo $get->getElementsByTagName('title')->item(0)->textContent;
}

That should solve the issue.