<?phpOutput:
header('Content-type: text/plain');
$xmlData = <<<XML
<?xml version='1.0'?>
<trees>
<fruit>
<apple name='apple' type='Deciduous' has-fruit='Y' />
<pear name='pear' type='Deciduous' has-fruit='Y' />
</fruit>
<pine>
<white name='whitepine' type='Coniferous' has-fruit='N' />
</pine>
</trees>
XML;
$xml = simplexml_load_string($xmlData);
echo "Testing SimpleXml";
echo "\n".$xmlData;
echo "\nName:".$xml->fruit->apple->getName();
echo " Type:".$xml->fruit->apple->attributes()->type;
?>
Name:apple Type:Deciduous
However, if you decide to include a hyphen or a dash in the name of your attribute things get a bit more interesting. The code has to be adjusted since the name of a class method cannot contain "-". To make it work, the attribute name has to include braces and single quotes (e.g. "{'name'}").
echo "\n".$xmlData;Output:
echo "\nName:".$xml->fruit->apple->getName();
echo " Type:".$xml->fruit->apple->attributes()->type;
echo "\nFruit?:".$xml->fruit->apple->attributes()->{'has-fruit'};
Name:apple Type:Deciduous
Fruit?:Y
2 comments:
You saved me some hours !
Note that the problem also occurs if element contains dash, this not only happen for attributes.
using this method of accessing attributes will also avoid this problem
$xml->child['attr-ibute']
Post a Comment