I have this form given:
<item><parameter name="a">3</parameter></item>
Is it possible to read the "a" with SimpleXML?
I have already tried $xml->item->parameter->getName(); but it only returns "parameter".
Thanks in advance.
Yes, use the attributes()
method from SimpleXML
echo (string)$xml->item->parameter->attributes()->name;
Alternative solution is using xpath()
$name = $xml->xpath('item/parameter/@name');
echo $name[0];
xpath()
always returns array (or false in case of error), this why you need to assign it to a var, or if you have php >= 5.4 you can use array dereferencing
echo $xml->xpath('item/parameter/@name')[0];
Read about the SimpleXML function : attribute().
You can use it to get all attributes of an element.
In your case :
$attr = $xml->item->parameter->attributes();
$name = $attr['name'];
see 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,"\"
";
}
// output
name="a"