2012-07-05 36 views
1

我有這樣的形式給出:讀取參數的名稱用SimpleXML

<item><parameter name="a">3</parameter></item> 

是否可以讀取「一」與SimpleXML的?我已經嘗試過$ xml-> item-> parameter-> getName();但它只返回「參數」。

在此先感謝。

回答

4

是,使用該方法attributes()SimpleXML

SimpleXML::attributes()

echo (string)$xml->item->parameter->attributes()->name; 

codepad example


替代解決方案是使用xpath()

SimpleXML::xpath()

$name = $xml->xpath('item/parameter/@name'); 
echo $name[0]; 

codepad example

xpath()總是返回數組(或虛假的錯誤的情況下),這就是你需要將其分配給一個變種,或者如果你有PHP> = 5.4可以使用array dereferencing

echo $xml->xpath('item/parameter/@name')[0]; 
+0

非常感謝您! – Baloo 2012-07-05 10:45:51

3

閱讀有關的SimpleXML功能:attribute()

您可以使用它來獲取元素的所有屬性。
你的情況:

$attr = $xml->item->parameter->attributes(); 
$name = $attr['name']; 
+0

非常感謝! – Baloo 2012-07-05 10:46:01