2012-09-06 83 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.

相關問題