Wednesday, June 17, 2009

PHP dash in class and method names

I ran into what seems like a common issue when working with PHP and SimpleXML today. Parsing XML is normally pretty easy:
<?php
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;
?>
Output:
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;
echo "\nName:".$xml->fruit->apple->getName();
echo " Type:".$xml->fruit->apple->attributes()->type;
echo "\nFruit?:".$xml->fruit->apple->attributes()->{'has-fruit'};
Output:
Name:apple Type:Deciduous
Fruit?:Y

2 comments:

dragibus said...

You saved me some hours !
Note that the problem also occurs if element contains dash, this not only happen for attributes.

Robin Kirk said...

using this method of accessing attributes will also avoid this problem
$xml->child['attr-ibute']