使用php解析XML格式

使用php解析XML格式,php,xml,parsing,Php,Xml,Parsing,我试图使用PHP解析Xml文件,但每当我运行代码时,mit都会给我错误:为foreach()提供的参数无效 XML PHP代码: $xml = simplexml_load_string(file_get_contents('XML/STKCatigories.xml')); $i = 0; foreach($xml->Rows->Row as $key=>$product) { echo '<li>'.anchor ('/shop/listing

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

XML


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

}
$xml=simplexml\u load\u字符串(file\u get\u contents('xml/STKCatigories.xml');
$i=0;
foreach($xml->Rows->Row as$key=>$product){
回显“
  • ”.anchor(“/shop/listings/”.$product->Code,$product->Name)。“
  • ”; }
    我不明白我错在哪里。请帮助我

    $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));
    }
    
    $xml=simplexml\u load\u字符串(file\u get\u contents('xml/STKCatigories.xml');
    $prifix='/shop/listings/';
    foreach($xml作为$row){
    $attr=$row->attributes();
    printf(“
  • %s
  • ”,锚点($prifix.$attr->Code,$attr->Name)); }
    您正在尝试访问标记属性,而不是显式值。 尝试以下方法:

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

    太棒了。但它重复给我$attr->Name,因为$attr->Name包含每个产品的重复类别名称。我如何避免重复$attr->Name?@9位如果我得到完整的xml,我可以告诉你更好的方法谢谢你回复我。由于一些限制,我无法在这里发布xml。如果你可以,我将不胜感激请点击此链接并在此处推荐更好的解决方案……。@Baba。您能帮我解决这个问题吗?
    $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"