PHP SimpleXML回声

时间:2016-09-19 10:31:35

标签: php parsing simplexml

我试图从远程xml文件中回显以下输出(如果ktg = 001)。 在此先感谢您的任何帮助

我想回应的输出:

name2
22 44

name3
55 65

位于远程网址的XML文件:

<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我的例子:

<?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 ;
   }
}
?>

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

$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";
            }
        }
    }
}