duanpu1111 2014-05-22 16:50
浏览 38
已采纳

使用PHP DOMDocument从XML中获取标记值

I have a XML file with the following contents:

<Klassen>
  <Klas>
     <Klas>HT1</Klas>
     <Omschrijving>Klas HT1</Omschrijving>
  </Klas>
  <Klas>
     <Klas>HT2</Klas>
     <Omschrijving>Klas HT2</Omschrijving>
  </Klas>
</Klassen>

I want to get the values from the second level Klas tag. I used the following PHP script, but it doesn't work;

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load($apiurl);
$hallo = $xmlDoc->getElementsByTagName('Klas');

foreach ($hallo as $book) {
   $result = $book->nodeValue;
   echo '<option value="'.$result.'">'.$result.'</option>';
}
?>

I can't change the tag names because it's not my API and also the creator of the API won't change it. What can I do to get the values (in this example) HT1 and HT2 into the select box?

Thank you!

  • 写回答

1条回答 默认 最新

  • douhuo0884 2014-05-22 17:10
    关注

    Here's a solution for you using DOMXpath:

    <?php
        $xml = <<<XML
    <Klassen>
      <Klas>
         <Klas>HT1</Klas>
         <Omschrijving>Klas HT1</Omschrijving>
      </Klas>
      <Klas>
         <Klas>HT2</Klas>
         <Omschrijving>Klas HT2</Omschrijving>
      </Klas>
    </Klassen>
    XML;
    
    
        $xmlDoc = new DOMDocument();
        $xmlDoc->loadXML($xml);
    
        $xpath = new DOMXpath($xmlDoc);
        $hallo = $elements = $xpath->query("//Klas/Klas");
    
        foreach ($hallo as $book) {
            $result = $book->nodeValue;
            echo '<option value="'.$result.'">'.$result.'</option>';
        }
    

    Output:

    <option value="HT1">HT1</option><option value="HT2">HT2</option>
    

    Here's an online working example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧