Search code examples
phpxmlsimplexml

How to visit the elements after using `simple_load_file()` to load an xml file


I intend to fetch some certain data from xml files. I used simple_load_file() to load an xml file and get the object elements, but I don't know how to visit them. The xml file is like following:

<?mxl version="1.0">
<metaData>
<Application version="1.0" type="32">
   <options>
       <section name="A">
           <description>...</description>
           ...
       <section name="B">
       ....
   </options>
</Application>
</metaData>

My code:

$xml = simplexml_load_file($url);
echo $xml->Application->version; // get the version but failed
echo $xml->Application->options->section...//I want to get the data from each section, but I don't know how to visit the elements.

Solution

  • Before i answer this question, let me tell you a little tip, whenever you have any problem try searching it on google, like in this case, i would search:

    PHP simplexml examples
    

    Ok, lets say we have a XML content:

    <?php
    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
    <movies>
     <movie>
      <title>PHP: Behind the Parser</title>
      <characters>
       <character>
        <name>Ms. Coder</name>
        <actor>Onlivia Actora</actor>
       </character>
       <character>
        <name>Mr. Coder</name>
        <actor>El Act&#211;r</actor>
       </character>
      </characters>
      <plot>
       So, this language. It's like, a programming language. Or is it a
       scripting language? All is revealed in this thrilling horror spoof
       of a documentary.
      </plot>
      <great-lines>
       <line>PHP solves all my web problems</line>
      </great-lines>
      <rating type="thumbs">7</rating>
      <rating type="stars">5</rating>
     </movie>
    </movies>
    XML;
    ?>
    

    We can parse the XML data this way:

    <?php
    
    
    $movies = new SimpleXMLElement($xmlstr);
    
    echo $movies->movie[0]->plot;
    ?>
    

    For more example please visit: http://php.net/manual/en/simplexml.examples-basic.php

    For this question specific, you should use the SimpleXMLElement::children