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."℃";
?>
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.
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."℃";
}