如何使用PHP的SimpleXML扩展遍历XML树?

时间:2014-07-09 12:15:27

标签: php xml simplexml

给出以下XML:

$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <DataService xmlns="http://www.example.com">
      <Response>
        <XMLRootNode xmlns="http://www.example.com">
          <ResponseHeader>
            <Version>2.0</Version>
            <RecordCount>2</RecordCount>
          </ResponseHeader>
          <OnlineInformation BoothID="12345">
            <EventID>4</EventID>
            ...

如何使用PHP的SimpleXML扩展程序访问EventID的内容?我用一个简单的示例表单here取得了成功,但我似乎无法遍历上面更复杂的树结构。我的基本代码如下。我希望$output包含值4。

$data = new SimpleXMLElement($xmlstr);

$output = $data->...

感谢。

1 个答案:

答案 0 :(得分:0)

您也可以DOMDocument。像这样:

// your incomplete xml sample
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
      <DataService xmlns="http://www.example.com">
        <Response>
          <XMLRootNode xmlns="http://www.example2.com">
            <ResponseHeader>
              <Version>2.0</Version>
              <RecordCount>2</RecordCount>
            </ResponseHeader>
            <OnlineInformation ExampleID="12345">
              <EventID>4</EventID>
            </OnlineInformation>
          </XMLRootNode>    
        </Response>
      </DataService>
    </soap:Body>
  </soap:Envelope>
XML;

$dom = new DOMDocument();
$dom->loadXML($xmlstr);
foreach($dom->getElementsByTagName('OnlineInformation') as $OnlineInformation) {
    if($OnlineInformation->getAttribute('ExampleID') == 12345) {
        echo $OnlineInformation->getElementsByTagName('EventID')->item(0)->nodeValue;
        // 4
    }
}

或者只需使用xpath并直接指出:

$xml = simplexml_load_string($xmlstr);
$xml->registerXPathNamespace('ns', 'http://www.example2.com');
$node = $xml->xpath('//ns:OnlineInformation[@ExampleID="12345"]')[0];
echo (string) $node->EventID; // 4