【问题标题】:xml attributes name error?xml属性名称错误?
【发布时间】:2013-01-19 18:20:39
【问题描述】:

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

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

当我尝试打印出 xdebug 给出的这 2 个属性 engine-type 和 body-style 时出现问题

$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
其他属性工作正常

【问题讨论】:

标签: php xml xml-parsing


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    这允许人们像这样动态地构造属性名称(在这种情况下不需要)

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

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

    示例#3 获取&lt;line&gt;

    <?php
    include 'example.php';
    
    $movies = new SimpleXMLElement($xmlstr);
    
    echo $movies->movie->{'great-lines'}->line;
    ?>
    

    上面的例子会输出:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-02
        • 1970-01-01
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        相关资源
        最近更新 更多