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

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

4 Comments

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 if i get the full xml i can tell you a better approach
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...stackoverflow.com/questions/12883586/xml-complex-parsing
@Baba.Could you please help me with this? stackoverflow.com/questions/26372398/…
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.