view raw
Webnet Webnet - 1 year ago 40
PHP Question

Accessing a numeric property in a SimpleXMLElement

I'm trying to access the number in the below element, but I'm having trouble getting the value out of it.

echo $object->0; //returns Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'

SimpleXMLElement Object (
[0:public] => 15810

Any ideas on how I can get that value?


I realize that this is an odd error... I'm using the ebay API to get this value. Even when I do:

$zero = 0;

It still shows the same

SimpleXMLElement Object (
[0:public] => 15810

I tried
as well

Here's the output of what I'm working with....

[1] => SimpleXMLElement Object (
[CallName:public] => AddItem
[CountsTowardAggregate:public] => false
[DailyHardLimit:public] => 100000
[DailySoftLimit:public] => 100000
[DailyUsage:public] => 0
[HourlyHardLimit:public] => 100000
[HourlySoftLimit:public] => 100000
[HourlyUsage:public] => 0
[Period:public] => -1
[PeriodicHardLimit:public] => 0
[PeriodicSoftLimit:public] => 0
[PeriodicUsage:public] => 0
[ModTime:public] => 2010-05-04T18:06:08.000Z
[RuleCurrentStatus:public] => NotSet
[RuleStatus:public] => RuleOn

So here's the thing...

number_format($ruleXml->HourlyUsage) //throws the error: number_format() expects parameter 1 to be double, object given

$ruleXml->HourlyUsage //shows the value on the page

$x = 0;
echo $object->$x;


echo $object->{0};

The reason is that '0' is not a valid identifier in PHP. So when you type '0', all it sees is a T_LNUMBER. All names follow the varaible naming convention. The only deviation is that a member variable preceded by a -> does not need the $ prefix.

{0} works, because {} indicates that the identifier is the result of the simple expression inside. So {$x} is the same as $x in this case, but {0} is not the same as '0', since they result in different parser tokens.