Search code examples
phphtmlxmlsimplexml

How to get a specific child from an XML file and show its children on a div with PHP


So, I have an XML file that looks like this (The names are fictional):

<myxmlfile>
  <infos>
     <item>
        <itemChild1>foo1</itemChild1>
        <itemChild2>foo2</itemChild2>
     </item>
     <item>
        <itemChild1>foo1</itemChild1>
        <itemChild2>foo2</itemChild2>
     </item>
     <item>
        <itemChild1>foo1</itemChild1>
        <itemChild2>foo2</itemChild2>
     </item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
  <infos>
</myxmlfile>

My goal is to take for example ONLY the third <item>, and show on my browser its children. How can I achieve that?

So far I have this:

PHP

<?php
$divId = 0;
$url ='myxml.xml';
$xml = simplexml_load_file($url) or die ("Can't connect to URL");
?>

Solution

  • The simplest way to access the node values of your XML would be to use the object operator plus your node name e.g. $xml->myxmlfile

    $xml_data = '
        <myxmlfile>
          <infos>
             <item>foo1</item>
             <item>foo2</item>
             <item>foo3</item>
             <item>foo4</item>
             <item>foo5</item>
          </infos>
        </myxmlfile>
    ';
    
    $xml = new SimpleXMLElement($xml_data);
    
    foreach($xml->infos->item as $k=>$v) {
    
        echo $v . '<br>';
    
    }
    

    Output:

    foo1
    foo2
    foo3
    foo4
    foo5
    

    See: http://php.net/manual/en/book.simplexml.php