使用PHP XML Reader获取上下文中节点的信息

时间:2015-05-07 19:56:34

标签: php xml parsing xmlreader

@those谁将此问题标记为重复,请发表评论,为什么您认为这是重复的。在这里,我们希望获得某个节点中的所有元素。在另一个问题中,他们希望得到父节点。这几乎是相反的。在这里,我们不是选择人员节点及其子节点,而是在上下文中获取任何人。我觉得它看起来很相似。

问题: 要明确:我想用XML Reader做到这一点。

我有一个XML文件,想要在上下文中检索名称节点的内容。名称节点也出现在汽车中,这就是我需要上下文的原因。

我该怎么做?

<file>
  <people>
     <person>
        <name>father</name>
        <age>50</age>
     </person>
  </people>
  <car>
     <person>
        <name>mom</name>
        <age>45</age>
     </person>
     <name>Octavia</name>
     <brand>Scoda</brand>
  </car>
  <people>
     <person>
        <name>son</name>
        <age>25</age>
     </person>
     <person>
        <name>daughter</name>
        <age>20</age>
     </person>
  </people>

这是我到目前为止获得的PHP:

$xmlReader = new XMLReader;

if (!$xmlReader->open($this->_file, null, 1<<19)) {
   die("Failed to open file");
}


while($xmlReader->read()) {
    // set the context
    if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'people') {
          // do something with the name of every person
          if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'person') {
              $xmlReader->name->readString();
          }
    }
}

1 个答案:

答案 0 :(得分:1)

这是代码:

$xmlReader = new XMLReader;

if (!$xmlReader->open($fileURL, null, 1<<19)) {
   die("Failed to open file");
}
while($xmlReader->read()) {
    if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'people') {
// We are at the beginning of the node people. 
        while ($xmlReader->read()) {
            if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'person') {
// We are at the beginning of the node person. 
                while ($xmlReader->read()) {
                    if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'name' && $xmlReader->read())
// And now node 'name. Then we make one read more to step to 'TEXT' type of node. Because 'ELEMENT' does not have value         
                        echo $xmlReader->value.'<br>';
                    else if ($xmlReader->nodeType == XMLReader::END_ELEMENT && $xmlReader->name == "person")
// This is closing element of node 'persons. Interrupt loop 
                        break;
                }
            }
            if ($xmlReader->nodeType == XMLReader::END_ELEMENT && $xmlReader->name == "people")
// This is closing element of node 'people. Interrupt loop 
                        break;
        }
    }
}

输出:

futher
son
daughter

<强>更新 或者将节点'person'放到simplexml对象中。然后循环看起来像:

while($xmlReader->read()) {
    if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'person') {           
        $xml = new SimpleXMLElement($xmlReader->readOuterXML());
        foreach ($xml->name as $name)
            echo $name.'<br>';
   }
}