2016-03-01 70 views
1

這是我的示例對象。我需要使用數組訪問對象。但我不能訪問這個場景的數組,因爲特殊字符(@)是前綴。所以請幫助我如何訪問陣列。在特定字符的php中關聯數組的關鍵更改

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [Reference] => 758 
      [Key] => P201602161758028991205395 
     ) 

) 
+3

Objects!== arrays ....如果您需要訪問屬性,然後使用[SimpleXMLElement :: attributes](http://www.php.net/manual/en/simplexmlelement.attributes.php) –

+0

'$ obj - > {'@ attributes'} ['Key']' – h2ooooooo

+1

請RTFM,示例#5,訪問屬性:http://php.net/manual/en/simplexml.examples-basic.php – deceze

回答

2

您可以直接訪問這些屬性,例如,

echo $elem["Reference"]; 
echo $elem["Key"]; 

正如@馬克貝克指出正確的方向,的SimpleXML實際奇蹟發生在幕後。正如@deceze所提到的,這是針對SimpleXML的

你甚至可以遍歷他們:

foreach($xml->foo[0]->attributes() as $a => $b) { 
    echo "$a = $b \n"; 
} 
+1

您應該明確指出這是針對SimpleXML的... – deceze

+1

@deceze:剛剛做完了。 – Jan

2

您可以訪問單個屬性直接作爲@簡的答案節目。

如果你需要抓住所有的屬性作爲一個真正的數組,這是做這件事:

$attributes = current($element->attributes()); 

我寧願這是一個緊張的,濃縮的方式來抓住所有的屬性沒有循環數組。

相關問題