使用PHP导入XML,不接受XML标记中的" - "

Sna*_*ker 3 html php xml tags import

这有点像我的XML:

<?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> 
Run Code Online (Sandbox Code Playgroud)

现在,我想使用PHP导入标签"rank-points"中的内容

$rank = $xml->{'military'}->rank-points;
Run Code Online (Sandbox Code Playgroud)

但是,因为XML标签的名称中带有" - ",所以它不起作用.结果始终为0.

Pas*_*TIN 6

使用这个:

$rank = $xml->{'military'}->rank-points;
Run Code Online (Sandbox Code Playgroud)

PHP实际上会:

  • 搜索 $xml->{'military'}->rank
  • 并尝试将常量的值减去该points
    • 如果不存在,它将使用字符串值"points".

试图执行你的代码,你应该得到一个通知,说明我说的话:

Notice: Use of undefined constant points - assumed 'points'
Run Code Online (Sandbox Code Playgroud)


要解决该问题,请尝试添加{''}标记名称:

$rank = $xml->{'military'}->{'rank-points'};
Run Code Online (Sandbox Code Playgroud)

这样,PHP就会知道这rank-points是一回事 - 而不是减法.