使用SimpleXMLElement :: xpath()时语法上的奇怪错误

时间:2013-07-15 17:05:48

标签: php simplexml

所以,我有一些像这样的代码:

$xml = simplexml_load_file( $configuration_path . $this->configuration_file );

// some stuff in between, not important

// next line would be line 80, where the parser whines
$this->ping_tree_1 = ( string ) (( $xml->xpath( '//ping-tree[@order="1"]' ))[0] );

现在,它似乎对我有用,但我一直收到这个错误:

Parse error: syntax error, unexpected '[' in models/site_configuration.php on line 80

如果我注释掉有问题的行并执行:

print_r( $xml->xpath( '//ping-tree[@order="1"]' ));
die;

我看到以下内容被退回:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [order] => 1
                )

            [0] => dd0d7afa2414fc1d3ddc18c87351478f
        )

)

这正是我的预期。

甚至更多有趣的是,当我这样做时:

$_xml = $xml->xpath( '//ping-tree[@order="1"]' );
$this->ping_tree_1 = ( string ) $_xml[0];

一切正常就好了

那么...给出了什么?有人知道吗?这是一个PHP解析错误,还是只是我密集?

顺便说一下,这完全在Apache / 2.2.22(Unix)下的PHP / 5.2.17上。

谢谢!

1 个答案:

答案 0 :(得分:1)

查看阵列上的手册页:http://php.net/manual/en/language.types.array.php

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable

您正在尝试使用此代码:

$this->ping_tree_1 = ( string ) (( $xml->xpath( '//ping-tree[@order="1"]' ))[0] );

您尝试使用的语法在5.4中引入,您使用的是5.2。你已经看到你可以用一个临时变量解决这个问题;您的替代方案是更新到PHP的更高版本。