Brian Bruman Brian Bruman - 1 year ago 86
PHP Question

GetElementsByTagName only returning first node in array

I am trying to get each element in the array using


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

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

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

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

How do I ensure I loop over
and get every possible iteration of
in every

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download