Search code examples
phpparsingsimplexml

PHP SimpleXML echo


I am trying to echo the following output (if ktg=001) from a remote xml file. Thanks in advance for any help

Output that I'd like to echo:

name2
22 44

name3
55 65

XML file located in remote url:

<aaa id="AA" epg="AA" ktg="001">
<Name>john</Name>
<Customer id="0001">
  <Name>name2</Name>
  <Dfr>0</Dfr>
  <Date>09/19/2016 13:20:00</Date>
  <ktopt>No</ktopt>
  <SOS type="BB" id="0002">
      <age name="df1">22</age>
      <age name="df2">44</age>
  </SOS>
</Customer>
<Customer id="0002">
  <Name>name3</Name>
  <Dfr>0</Dfr>
  <Date>09/20/2016 06:20:00</Date>
  <Ktopt>No</Ktopt>
  <SOS type="CC" id="0004">
     <age name="df1">55</age>
     <age name="df2">65</age>
  </SOS>
</Customer>
</aaa>

PHP my example :

<?php

$url = 'http://remotexmllocationonforexample';
$obj = simplexml_load_file($url);
  foreach ($obj->aaa as $aaa) {
    if ( $aaa['ktg'] == '001') {    
    echo  $aaa->Customer->Name ; 
    echo '  <br />';  
    echo  $aaa->Customer->SOS ;
   }
}
?>

Solution

  • You can try this code:

    $url = 'http://remotexmllocationonforexample';
    $obj = simplexml_load_file($url);
    
    foreach ($xml as $aaa) {
        $attr = $aaa->attributes();
         if($attr['ktg']=='001') {
            $xmlData = get_object_vars($aaa);
             foreach($xmlData['Customer'] as $cust) {
                $custDetais = get_object_vars($cust);
                 echo "Name: ".$custDetais['Name'].PHP_EOL;
                 foreach($custDetais['SOS'] as $sos) {
                     echo $sos[0]."\t";
                }
            }
        }
    }