2011-06-14 82 views
1

我使用PHP和Simple XML。PHP - 簡單的XML屬性問題

我用一個循環,並不像預期的工作:

foreach($item->Image->attributes()->source as $key => $value) 
{ 
    echo $value; 
} 

在foreach我試着告訴我要得到它在屬性中列出的圖像的「來源」。

$item上面用在我的代碼迴路以上foreach($xml_content->Section->Item as $item {}創建,(如果你需要知道它是從哪裏來的)

我的目標是這樣的:

object(SimpleXMLElement)#36 (4) { 
    ["Text"]=> 
     string(15) "Vinbergs socken" 
    ["Description"]=> 
     string(73) "Vinbergs socken ingick i Faurås härad och ligger i Falkenbergs kommun. 
    " 
    ["Url"]=> 
     string(44) "http://sv.wikipedia.org/wiki/Vinbergs_socken" 
    ["Image"]=> 
     object(SimpleXMLElement)#38 (1) { 
      ["@attributes"]=> 
        array(3) { 
         ["source"]=> 
          string(113) "http://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Faur%C3%A5s_Vinberg.svg/50px-Faur%C3%A5s_Vinberg.svg.png" 
         ["width"]=> 
          string(2) "50" 
         ["height"]=> 
          string(2) "41" 
         } 
      } 
    } 

什麼是錯的與我的循環在我的職位開始?

+0

你的錯誤/問題是什麼? – 2011-06-14 08:26:09

回答

5

你正試圖遍歷字符串,而不是一個數組

$item->Image->attributes()->source 

要遍歷圖像元素的所有屬性,可以使用

foreach ($item->Image->attributes() as $attributeName => $attributeValue) { 

如果你只是要輸出的值源屬性,不重複但使用速記

echo $item->Image['source'] 

看到這個demoSimpleXml Basic Usage Examples in the PHP Manual