0

I am trying to parse Xml file using PHP but whenever i runs the code mit gives me error: invalid argument supplied for foreach()

XML

<?xml version="1.0" standalone="yes"?>  
<Rows>
<Row Code="10004" Name="EDEN 46cm TROUGH  Terracotta"  />
</Rows>

PHP code:

$xml =  simplexml_load_string(file_get_contents('XML/STKCatigories.xml'));
$i = 0;
   foreach($xml->Rows->Row as $key=>$product) {

  echo '<li>'.anchor ('/shop/listings/'.$product->Code,$product->Name).'</li>';

}

I couldn't understand where i am wrong.Kindly help me

9 Digit
  • 167
  • 2
  • 11

2 Answers2

1

It should be

$xml =  simplexml_load_string(file_get_contents('XML/STKCatigories.xml'));
$prifix = '/shop/listings/' ;
foreach ( $xml as $row ) {
    $attr = $row->attributes();
    printf('<li>%s</li>', anchor($prifix . $attr->Code, $attr->Name));
}
Baba
  • 94,024
  • 28
  • 166
  • 217
  • Brilliant.But it is giving me $attr->Name repeatedly as $attr->Name contains repeated category name for each product.How can i avoid duplication of $attr->Name in this? – 9 Digit Oct 04 '12 at 07:17
  • @9 Digit if i get the full xml i can tell you a better approach – Baba Oct 04 '12 at 09:47
  • Thank you for getting back to me.I couldn't post the XML here due to some restriction.I will appreciate if you could follow this link and recommend a better solution here...http://stackoverflow.com/questions/12883586/xml-complex-parsing – 9 Digit Oct 14 '12 at 18:00
  • @Baba.Could you please help me with this? http://stackoverflow.com/questions/26372398/oop-challenge-how-to-nest-using-foreach-in-php-mysql-result-set – 9 Digit Oct 15 '14 at 11:51
0

You're trying to access tag attributes rather than explicit values. Try something like:

$str = <<<XML
<?xml version="1.0" standalone="yes"?>  
<Rows>
<Row Code="10004" Name="EDEN 46cm TROUGH  Terracotta"  />
</Rows>
XML;


$xml = simplexml_load_string($str);

foreach($xml->Row->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

Output:

SimpleXMLElement Object
(
    [Row] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [Code] => 10004
                    [Name] => EDEN 46cm TROUGH  Terracotta
                )

        )

)
Code="10004" Name="EDEN 46cm TROUGH Terracotta"
nickhar
  • 19,981
  • 12
  • 60
  • 73