Search code examples
phpxmlxmlreader

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>

Solution

  • 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');
            }
    }