2

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>
user1129107
  • 205
  • 1
  • 8
  • 16

2 Answers2

3

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');
        }
}
hakre
  • 193,403
  • 52
  • 435
  • 836
Wrikken
  • 69,272
  • 8
  • 97
  • 136
  • I tried that earlier, and again (see edit) and still do not get a result? – user1129107 Mar 13 '13 at 22:38
  • I get a result with this very code without a problem. Which means... you probably don't load the correct XML file? – Wrikken Mar 13 '13 at 22:39
  • Okay apparently it IS working... but I can only see it if I view source on my page when the script finishes? – user1129107 Mar 13 '13 at 22:46
  • Essentially what I want to do is store this attribute as a string, and then insert that string into a database. I now see that I am finding the attribute, but when I try to insert it to the database, it is blank table, much like my screen is showing nothing, without view-source. – user1129107 Mar 13 '13 at 22:50
  • That's another issue, blank screens usually mean fatal errors, enable `error_reporting` to report _all_ errors, and set `display_errors` ON, see also the question 'I have a typical "does not work" problem. What should I do before asking a question?' in the [php info page](http://stackoverflow.com/tags/php/info) – Wrikken Mar 13 '13 at 22:55
  • Okay nevermind. It works now? I don't know what the deal was there. Maybe I missed an upload or something. Taking out the read-> seemed to have worked. Thanks – user1129107 Mar 13 '13 at 22:57
2

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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836