0

我正在尝试使用 PHP 解析 Xml 文件,但每当我运行代码时,mit 都会给我错误:为 foreach() 提供的参数无效

XML

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

PHP代码:

$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>';

}

我不明白我错在哪里。请帮助我

4

2 回答 2

1

它应该是

$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));
}
于 2012-10-03T16:43:02.830 回答
0

您正在尝试访问标签属性而不是显式值。尝试类似:

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

输出:

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

        )

)
Code="10004" Name="EDEN 46cm TROUGH Terracotta"
于 2012-10-03T16:49:33.803 回答