开发者

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?

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


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


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)


You can use __toString() to get string value of child object ,so it will be like $object->__toString();


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜