duanjianshen4871 2014-07-09 12:15 采纳率: 100%
浏览 71

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

Given the following 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>
            ...

How can I access the contents of EventID using PHP's SimpleXML extension? I've had success with a simple example form here, but I cannot seem to traverse the more complex tree structure above. My basic code is below. I want $output to contain the value 4.

$data = new SimpleXMLElement($xmlstr);

$output = $data->...

Thanks.

  • 写回答

1条回答 默认 最新

  • dougan6982 2014-07-09 13:10
    关注

    You can alternatively you DOMDocument. Like this:

    // 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
        }
    }
    

    Or just use xpath and directly point it:

    $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
    
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改