dsafq2131321 2017-01-18 18:43
浏览 104
已采纳

通过属性simplexml获取值

I have this code to show some values from xml table on my webpage:

<?php
$xml=simplexml_load_file("http://www.arso.gov.si/xml/vode/hidro_podatki_zadnji.xml") or die("Error: Cannot create object");
echo "Merilno mesto: ".$xml->postaja[126]->merilno_mesto."<br>";
echo "Datum/ura: ".$xml->postaja[126]->datum."<br>";
echo "Vodostaj: ".$xml->postaja[126]->vodostaj." cm"."<br>";
echo "Pretok: ".$xml->postaja[126]->pretok." m<sup>3</sup>/s";
echo " - ".$xml->postaja[126]->pretok_znacilni."<br>";
echo "Temperatura vode: ".$xml->postaja[126]->temp_vode."&#x2103;";
?>

I use element number 126 to display some specific values on my webpage. This works OK, but the problem is that the row order in xml file is not always the same. So I want to get values by specific attribute, best one I think could be attribute "sifra". You could look at xml file in url in upper code block.

And sorry I am a newbie and I have also sarched of Questions, but I haven't get anything that I understand. On other words all answers appear too complicated for me according to my code which is quite simple.

Thanks for Your help.

  • 写回答

1条回答 默认 最新

  • douhuijun3776 2017-01-18 18:58
    关注

    You can use XPath to get a node by attribute with a certain value. You can use the method SimpleXMLElement::xpath to query the XML file like a database with XPath (instead of SQL).

    //load the xml file.
    $xml=simplexml_load_file("http://www.arso.gov.si/xml/vode/hidro_podatki_zadnji.xml") or die("Error: Cannot create object");
    
    //select a node with name "postaja" on parent with name "arsopodatki"
    //where attribute "sifra" on node "postaja" has the value "1165". 
    $xmlNodes = $xml->xpath('/arsopodatki/postaja[@sifra="1165"]');
    
    //is there a node?
    if (count($xmlNodes) < 1) {
        die('Node not found!'); //No
    } else {
        $xmlNode = $xmlNodes[0]; //Yes
        echo "Merilno mesto: ".$xmlNode->merilno_mesto."<br>";
        echo "Datum/ura: ".$xmlNode->datum."<br>";
        echo "Vodostaj: ".$xmlNode->vodostaj." cm"."<br>";
        echo "Pretok: ".$xmlNode->pretok." m<sup>3</sup>/s";
        echo " - ".$xmlNode->pretok_znacilni."<br>";
        echo "Temperatura vode: ".$xmlNode->temp_vode."&#x2103;";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作