dsafq2131321 2017-01-18 10: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 10: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;";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部