【问题标题】:XML parsing format using php使用php解析XML格式
【发布时间】:2012-10-03 16:37:30
【问题描述】:

我正在尝试使用 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>';

}

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

【问题讨论】:

    标签: php xml parsing


    【解决方案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));
    }
    

    【讨论】:

    • Brilliant.But 它给了我 $attr->Name 重复,因为 $attr->Name 包含每个产品的重复类别名称。我怎样才能避免 $attr->Name 重复?
    • @9 位数如果我得到完整的 xml,我可以告诉你更好的方法
    • 感谢您回复我。由于某些限制,我无法在此处发布 XML。如果您可以点击此链接并在此处推荐更好的解决方案,我将不胜感激...stackoverflow.com/questions/12883586/xml-complex-parsing
    • @Baba.你能帮我解决这个问题吗? stackoverflow.com/questions/26372398/…
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-20
      • 2010-11-10
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多