xml属性名称错误?

时间:2013-01-19 18:20:39

标签: php xml xml-parsing

我试图解析一个包含基本属性的简单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
其他属性正常工作

3 个答案:

答案 0 :(得分:3)

使用curly complex syntax表示带有特殊字符的标识符。

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

答案 1 :(得分:2)

engine-type在PHP中不是有效的标签名称,因此不能直接用于引用对象的属性。

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

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

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

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

我们有一个这种语法的示例,处理与问题中完全相同的场景,目前在SimpleXML Basic Usage手册页上以示例#3 的形式提供。

  

示例#3获取<line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>
     

以上示例将输出:

     
    

PHP解决了我所有的网络问题

  

答案 2 :(得分:1)

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

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

相关问题