tags:

views:

49

answers:

3

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?

Update

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

  $zero = 0;
  $print_r($ruleXml->HourlyUsage->$zero);

It still shows the same

SimpleXMLElement Object ( 
    [0:public] => 15810
)

I tried {0} 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
+2  A: 
$x = 0;
echo $object->$x;

or

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. http://www.php.net/manual/en/language.variables.basics.php

{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.

ircmaxell
Have you actually got that working? I highly doubt it would give the desired result.
Josh Davis
Yes. I tried, and it works as described...
ircmaxell
Interesting, it doesn't work at all on PHP 5.3.2 / libxml 2.7.7.
Josh Davis
A: 

XML elements cannot begin with a digit. Even if you can somehow create such elements, SimpleXML (and most likely, most parsers) will not be able to read the result document.

<!-- legal -->
<a0>foo</a0>

<!-- not legal -- note how even Stack Overflow's highlighter chokes on it -->
<0>foo</0>
Josh Davis
A: 

I don't know what that business about nodes named "0" but the error you're seeing is because SimpleXML always returns objects. If you have to use the result as a number, cast it to the appropriate type, e.g.

number_format((int) $ruleXml->HourlyUsage)
Josh Davis