2013-11-09 38 views
0

我從一個XML文件中檢索數據,像這樣如何從簡單的XML對象獲取某些細節?

$response = simplexml_load_file($url); 

的print_r顯示以下

SimpleXMLElement Object 
(
[artist] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [type] => Group 
       [id] => b9fb5447-7f95-4a6a-a157-afed2d7b9f4c 
      ) 

     [name] => He Is Legend 
     [sort-name] => He Is Legend 
     [country] => US 
     [area] => SimpleXMLElement Object 
      (
       [@attributes] => Array 
        (
         [id] => 489ce91b-6658-3307-9877-795b68554c98 
        ) 

       [name] => United States 
       [sort-name] => United States 
       [iso-3166-1-code-list] => SimpleXMLElement Object 
        (
         [iso-3166-1-code] => US 
        ) 

      ) 

    ) 

) 

這樣我就可以輸出領域,如名稱和國家

echo $response->artist->name; 
echo $response->artist->country; 

不過我當涉及到訪問屬性數組中的數據時,它就陷入了困境。 如何從第一個屬性數組中獲得組的類型,例如?

編輯

我也試圖從一個函數返回的細節,像這樣

func getDetails($id) { 

$response = simplexml_load_file('http://musicbrainz.org/ws/2/artist/'.$id); 
$data = array(); 
$data['type'] = $response->artist->attributes()->type; 
$data['country'] = $response->artist->country; 

return $data; 
} 

print_r(getDetails()); 

給我

MusicBrainz Object 
(
) 
+0

'$ response-> artist-> attributes()'將返回元素屬性的鍵/值對數組 –

回答

1

可以使用attributes()方法訪問它們:

echo $response->artist->attributes()->type; 

SimpleXML文檔中的example #5顯示了另一個示例。

+0

謝謝,它成功地輸出了值。然而,我正在做一個函數內部,並試圖將值保存到一個數組來返回它。 返回數據後,我剩下一個空對象。關於我能在這裏做什麼的任何想法? –

+0

@NickShears:你如何在函數內部使用它?沒有看到相關的代碼,我無法幫助。 :) –

+0

嘿我編輯我原來的帖子與代碼 –