Import XML with PHP, does not accept "-" in XML tag
This is somewhat what my XML looks like:
<?xml version="1.0" encoding="UTF-8"?>
<citizen>
<military>
<rank-points>62750</rank-points>
<stars>1</stars>
<total-damage>18243</total-damage>
<rank>Commander</rank>
<fight-count>0</fight-count>
</military>
</citizen>
Now, I want to import the st开发者_运维知识库uff inside the tag "rank-points" with PHP using
$rank = $xml->{'military'}->rank-points;
But, because the XML tag has a "-" in it's name, it won't work. The result is always 0.
Using this :
$rank = $xml->{'military'}->rank-points;
PHP will actually :
- search for
$xml->{'military'}->rank
- and try to substract the value of the constant
points
to that value- if the contant doesn't exist, it'll use the string value
"points"
.
- if the contant doesn't exist, it'll use the string value
Trying to execute your code, you should actually get a notice, indicating what I said :
Notice: Use of undefined constant points - assumed 'points'
To solve that problem, try adding {''}
around the name of your tag :
$rank = $xml->{'military'}->{'rank-points'};
This way, PHP will know that rank-points
is one thing -- and not a substraction.
You'll have to encapsulate the rank-points
in curly braces as well:
$rank = $xml->{'military'}->{'rank-points'};
PHP assumes that you're trying to substract the contant "point" from the variable $rank.
The SimpleXML documentation has an example demonstrating exactly this problem; accessing elements within an XML document that contain characters not permitted under PHP's naming convention. The solution is to use an inline variable property, which basically means (in your case) wrapping the property name in {'
and '}
.
It is interesting that you chose to wrap military
in the curly-brace syntax, albeit unnecessarily as it contains a perfectly valid plain property name (c.f. rank-points
).
So your example could simply become:
$rank = $xml->military->{'rank-points'};
精彩评论