简体   繁体   English

使用XMLReader和PHP获取XML属性

[英]Getting XML Attribute with XMLReader and PHP

I don't understand why I can't reference the XML Attribute 'headendId'. 我不明白为什么我不能引用XML属性'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) (xml是)

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

Don't advance to the next node with ->read() once you found it (an attribute is not a node): 找到它后,不要使用->read()进入下一个节点 (属性不是节点):

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

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. XMLElementIterator允许迭代特定元素,在这里您需要headend元素。

Then on each element you can call the getAttribute() method to fetch the string value of the headend headendId attribute. 然后,可以在每个元素上调用getAttribute()方法来获取headend headendId属性的字符串值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM