user1129107
user1129107

Reputation: 225

Getting XML Attribute with XMLReader and PHP

I don't understand why I can't reference the XML Attribute 'headendId'. I've referenced several posts on this and my syntax seems to be fine? Can someone explain what I am doing wrong? Thanks in advance.

<?php
$reader = new XMLReader();
$reader->open('file.xml');

while($reader->read())
{
    if($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'headend')
{   
//$reader->read();
$headend = (string)$reader->getAttribute('headendId');
echo $headend;
}
} 

(xml is)

<lineup>
 <headend headendId="something">
  <name>some name</name>
  <ids>ids</ids>
  <codes>codes</codes>
 </headend>
</lineup>

Upvotes: 2

Views: 4988

Answers (2)

Wrikken
Wrikken

Reputation: 70480

Don't advance to the next node with ->read() once you found it (an attribute is not a node):

while ($reader->read())
{
        if ($reader->nodeType === XMLREADER::ELEMENT 
            && $reader->localName === 'headend')
        {
                echo $reader->getAttribute('headendId');
        }
}

Upvotes: 3

hakre
hakre

Reputation: 197767

It works similar as outlined last time:

require('xmlreader-iterators.php'); // https://gist.github.com/hakre/5147685

$elements = new XMLElementIterator($reader, 'headend');
foreach ($elements as $element) {
    echo $element->getAttribute('headendId'), "\n";
}

The XMLElementIterator allows to iterate over specific elements only, here you want the headend elements.

Then on each element you can call the getAttribute() method to fetch the string value of the headend headendId attribute.

Upvotes: 2

Related Questions