2011-01-22 61 views
1

我正在制作一个脚本,它读取通过的XML文件并显示源代码。我已经完成了,但项目属性..我找不到方法来捕捉它们。下面的代码:PHP - 如何使用simpleXML读取XML项目的所有属性?

$xml = simplexml_load_file("path/to/file.xml"); 

    showTree($xml->children(), 0); 

    function showTree($value, $i) { 

     if($value == '') { 

      foreach($value as $name2 => $value2) { 

       echo str_repeat('--', $i)." <$name2> \n"; 
        showTree($value2, ($i+1)); 
       echo str_repeat('--', $i)." </$name2> \n"; 
      } 

     } else { echo str_repeat('--', $i)." ".trim($value)."\n"; } 

    } // end: function 

正如我所说的,它工作正常,但不显示的属性,例如:

<item id=2>Item</item> 

只返回:

<item>Item</item> 

感谢任何回应,迈克。

回答

1

除非我missread你的代码是这样的可能应该是正确的。

$xml = simplexml_load_file("path/to/file.xml"); 

    showTree($xml->children(), 0); 

    function showTree($value, $i) { 

     if($value == '') { 

      foreach($value as $name2 => $value2) { 

       $attribsStr = ''; 
       foreach($value2->attributes() as $attribName => $attribValue) { 
       $attribsStr .= $attribName . '="' . $attribValue . '"' . ' '; 
       } 

       echo str_repeat('--', $i)." <$name2 $attribsStr> \n"; 
       showTree($value2, ($i+1)); 
       echo str_repeat('--', $i)." </$name2> \n"; 
      } 

     } else { echo str_repeat('--', $i)." ".trim($value)."\n"; } 

    } // end: function 
+0

这正是我一直在寻找!非常感谢。 :-) – Mike 2011-01-22 21:33:55