Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP导入XML,不接受-&引用;在XML标记中_Php_Html_Xml_Import_Tags - Fatal编程技术网

使用PHP导入XML,不接受-&引用;在XML标记中

使用PHP导入XML,不接受-&引用;在XML标记中,php,html,xml,import,tags,Php,Html,Xml,Import,Tags,这就是我的XML看起来的样子: <?xml version="1.0" encoding="UTF-8"?> <citizen> <military> <rank-points>62750</rank-points> <stars>1</stars> <total-damage>18243</total-damage> <rank>

这就是我的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> 
但是,因为XML标记的名称中有一个“-”,所以它无法工作。结果始终为0。

使用以下方法:

$rank = $xml->{'military'}->rank-points;
PHP实际上将:

  • 搜索
    $xml->{'millitary'}->rank
  • 并尝试将常量
    点的值减去该值
    
    • 如果contant不存在,它将使用字符串值
      “points”
尝试执行代码时,您实际上应该得到一个通知,指出我所说的:

Notice: Use of undefined constant points - assumed 'points'

要解决此问题,请尝试在标记名称周围添加
{'}

$rank = $xml->{'military'}->{'rank-points'};

通过这种方式,PHP将知道
秩点
是一回事,而不是一个减法。

您还必须将
秩点
封装在大括号中:

$rank = $xml->{'military'}->{'rank-points'};

PHP假设您正试图从变量$rank中减去contant“点”。

SimpleXML文档正好演示了这个问题;访问XML文档中包含PHP命名约定不允许的字符的元素。解决方案是使用,这基本上意味着(在您的案例中)将属性名称包装在
{'
}

有趣的是,您选择了用大括号语法包装
军事
,尽管这是不必要的,因为它包含一个完全有效的普通属性名称(c.f.
秩点

因此,您的示例可以简单地变成:

$rank = $xml->military->{'rank-points'};
$rank = $xml->military->{'rank-points'};