我有這樣的形式給出:讀取參數的名稱用SimpleXML
<item><parameter name="a">3</parameter></item>
是否可以讀取「一」與SimpleXML的?我已經嘗試過$ xml-> item-> parameter-> getName();但它只返回「參數」。
在此先感謝。
我有這樣的形式給出:讀取參數的名稱用SimpleXML
<item><parameter name="a">3</parameter></item>
是否可以讀取「一」與SimpleXML的?我已經嘗試過$ xml-> item-> parameter-> getName();但它只返回「參數」。
在此先感謝。
是,使用該方法attributes()
從SimpleXML
echo (string)$xml->item->parameter->attributes()->name;
替代解決方案是使用xpath()
$name = $xml->xpath('item/parameter/@name');
echo $name[0];
xpath()
總是返回數組(或虛假的錯誤的情況下),這就是你需要將其分配給一個變種,或者如果你有PHP> = 5.4可以使用array dereferencing
echo $xml->xpath('item/parameter/@name')[0];
閱讀有關的SimpleXML功能:attribute()。
您可以使用它來獲取元素的所有屬性。
你的情況:
$attr = $xml->item->parameter->attributes();
$name = $attr['name'];
非常感謝! – Baloo 2012-07-05 10:46:01
看到http://php.net/manual/en/simplexmlelement.attributes.php
XML:
<item>
<parameter name="a">3</parameter >
</item>
PHP:
$xml = simplexml_load_string($string);
foreach($xml->parameter [0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
// output
name="a"
非常感謝您! – Baloo 2012-07-05 10:45:51