Search code examples
phpcurlsimplex

simplexml_load_string foreach doesnt display anything


My PHP code looks like below, it shows blank i want to Display all the records with hyperlinks like

<a href="test.php?id=$Id">$Name</a>

where $Id, $Name is from XML feed

  $path = 'www.abc.com/test.xml';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $path);
  curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  $returned = curl_exec($ch);
  curl_close($ch);
  // $xml === False on failure
  $xml = simplexml_load_string($returned);

foreach( $xml->Name as $Name){
   print (string)$Name;
}

MY XML looks like below

<ABCXml version="1.1.0">
  <Manufacturers>
   <Item>
    <Id>219</Id>
    <Name>Matrix Corp</Name>
   </Item>
   <Item>
    <Id>2040</Id>
    <Name>Microcomputer</Name>
   </Item>
 </Manufacturers>
</ABCXml>

Solution

  • Your xml object starts with Manufacturers which contains multiple Items which contain the Names and IDs. You need to path out to them.

    foreach($xml->Manufacturers->Item as $item) {
        printf("<a href='test.php?id=%s>%s</a>", $item->Id, $item->Name);
    }