2011-01-22 114 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