XML属性名称错误


xml attributes name error?

我试图解析一个包含基本属性的简单XML字符串

<hash>
<engine-type>
I4 DI
</engine-type>
<body-style>
SAV 4D
</body-style>
<year>
2012
</year>
</hash>

问题发生时,我试图打印出这两个属性引擎类型和身体风格的xdebug给出错误

$result = simplexml_load_string($query);
$enginetype = $result->engine-type;
$bodystyle = $result->body-style ;
echo $enginetype .'<br />'. $bodystyle ;

这些错误来自于xdebug

Notice: Use of undefined constant type - assumed 'type'
Notice: Use of undefined constant style - assumed 'style

当我试图将它们保存到数据库时值为0
其他属性就可以了

使用复杂花括号语法表示带有特殊字符的标识符。

$enginetype = $result->{'engine-type'};
$bodystyle = $result->{'body-style'} ;

engine-type在PHP中不是一个有效的标签名,所以不能直接用来引用对象的属性。

PHP允许"可变属性",使用花括号语法,接受属性名作为某个表达式的结果:该表达式可以像字符串一样简单。

$result->{'engine-type'};

允许动态地构造属性名(在这种情况下不需要),如

$var = 'bar';
$result->{'foo-'.$var};

我们有一个这种语法的例子,处理与问题中完全相同的场景,目前可以在SimpleXML基本使用手册页面上找到 example #3

例3获取<line>

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie->{'great-lines'}->line;
?>
上面的示例将输出:

PHP解决了我所有的web问题

问题是您的表达式被解释为变量$result->engine减去常数type。试试这个:

var_dump($result->{'engine-type'});