2012-09-06 85 views
2

我有一个带有两个破折号的标签的xml文档,如下所示:<item--1>。我使用SimpleXML来解析这个文档,所以它给了我对象属性和标签的名字。这显然是一个问题,我猜是因为破折号是变量和属性名称的无效字符。引用名称中具有破折号的对象属性

<?php 

$xml = "<data><fruits><item>apple</item><item--1>bananna</item--1></fruits></data>"; 

$xml = simplexml_load_string($xml); 

foreach($xml->children() as $child) { 
    var_dump($child->item); 
# var_dump($child->item--1); 
} 

当你运行它,你会得到

object(SimpleXMLElement)#5 (1) { 
    [0]=> 
    string(5) "apple" 
} 

但是,如果你取消注释最后一行,以两个破折号XML元素,你会得到一个错误:

PHP Parse error: syntax error, unexpected T_LNUMBER in test.php on line 17 

我试着使用大括号:

var_dump($child->{item--1}); 

但这只不过是给了我这个错误:

PHP Parse error: syntax error, unexpected T_DEC 

是递减运算符,或--

如何引用此对象上的属性?

+0

'var_dump($ child)'产生了什么? –

+0

'对象(的SimpleXMLElement)#4(2){ [ “项目”] => 串(5) “苹果” [ “项目 - 1”] => 串(7) “bananna” } '虽然它没有中断,但并不真正允许我访问数据。它们不是我可以参考的数组元素。 – user151841

+0

[我如何使用带连字符的名称访问此对象属性?](http://stackoverflow.com/questions/758449/how-do-i-access-this-object-property-with-a-hyphenated -名称) – hakre

回答

4

你用大括号的做法是不是太错,但你需要花括号之间的串:

var_dump($child->{'item--1'}); 
1

manual's pageSimpleXMLElement对象:

Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)

<subscribe> 
    <callback-url>example url</callback-url> 
</subscribe> 

In order to access the callback-url you will need to do something like the following:

<?php 
    $xml = simplexml_load_string($input); 
    $callback = $xml->{"callback-url"}; 
?> 

If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.

相关问题