Search code examples
phpxmlsimplexml

Reading multilevel XML with PHP (SimpleXML)


I'm struggling with PHP code that would read following XML file:

<putovanja agencija="Kompas Zagreb d.d.">
  <putovanje url="http://www.kompas.hr/Packages/Package.aspx?idPackage=3151" tip="Krstarenja Jadranom" destinacija="Krstarenja" naziv="Mini Krstarenje Jadranom Zadar-Opatija (5 noći, jedan smjer) " id="3151" polazak="Zadar (Krstarenje)">
    <ukrcaji>
      <ukrcaj>Zadar</ukrcaj>
    </ukrcaji>
    <datumiIcijene>
      <data od="28.08.2017" do="02.09.2017" cijena="3695"/>
      <data od="04.09.2017" do="09.09.2017" cijena="3360"/>
      <data od="11.09.2017" do="16.09.2017" cijena="3360"/>
    </datumiIcijene>
  </putovanje>
  <putovanje url="http://www.kompas.hr/Packages/Package.aspx?idPackage=3151" tip="Odmor" destinacija="Krstarenja" naziv="Mini Krstarenje Jadranom Zadar-Opatija (5 noći, jedan smjer) " id="3151" polazak="Zadar (Krstarenje)">
    <ukrcaji>
      <ukrcaj>Zadar</ukrcaj>
    </ukrcaji>
    <datumiIcijene>
      <data od="28.08.2017" do="02.09.2017" cijena="3695"/>
      <data od="04.09.2017" do="09.09.2017" cijena="3360"/>
    </datumiIcijene>
  </putovanje>
</putovanja>

I found sample online, more specifically on w3schools(https://www.w3schools.com/php/php_xml_simplexml_get.asp), I understand my XML is more complex, but I can't even get the URL of first "CHILD". I think loop goes trough right child as it write BREAK twice in the output. Does anyone have any clue where I made a mistake?

I'm really sorry if my question is stupid, I'm still learning how to code.

Thanks for all the help and wish you all a nice day :D

oh and my current code:

<?php
$xml=simplexml_load_file("putovanja.xml") or die("Error: Cannot create object");
foreach($xml->children() as $putovanja) {
    echo $putovanja->putovanje['url'];
    echo "Break <br>";
}
?>

Solution

  • Here is how to access the URLs:

    $xml=simplexml_load_file("putovanja.xml") or die("Error: Cannot create object");
    
    foreach($xml->putovanje as $p) {
        echo $p->attributes()->url;
        echo "\n";
    }
    

    You don't need children() and you'll find attributes() useful

    To access more elements then here is an example:

    <?php
    $xml=simplexml_load_file("putovanja.xml") or die("Error: Cannot create object");
    
    foreach($xml->putovanje as $p) {
        echo $p->attributes()->url;
        echo "\n";
        echo $p->ukrcaji->ukrcaj;    
        echo "\n";    
        echo $p->datumiIcijene->data[0]->attributes()->od;           
        echo "\n\n";
    }
    

    If you add print_r($p); within the loop then you'll see the data structure and be able to follow my example and access the other elements you need.