XML到PHP问题与未定义的变量

时间:2014-03-29 03:37:22

标签: php xml

所以我从api xml调用返回:

在浏览器中:

string(1005) " 0 0 56000 steadfast shared semidedicated dedicated vps vps_solusvm london shared vps vps_solusvm australia sis_group shared vps_solusvm 0.017 s 0.010 s 8676395012 "

在Google Chrome Elements中:

<ampa>
<command></command>0
<error_code>0</error_code>
<ttl>56000</ttl>
<datacenters>
    <n0>
        <name>steadfast</name>
        <description><!--[CDATA[SteadFast/Chicago, United States]]--></description>
        <services>
            <n0>shared</n0>
            <n1>semidedicated</n1>
            <n2>dedicated</n2>
            <n3>vps</n3>
            <n4>vps_solusvm</n4>
        </services>
    </n0>
    <n1>
        <name>london</name>
        <description><!--[CDATA[BlueSquare/London, United Kingdom]]--></description>
        <services>
            <n0>shared</n0>
            <n1>vps</n1>
            <n2>vps_solusvm</n2>
        </services>
    </n1>
    <n2>
        <name>australia</name>
        <description><!--[CDATA[Global Switch/Sydney, Australia]]--></description>
        <services>
        </services>
    </n2>
    <n3>
        <name>sis_group</name>
        <description><!--[CDATA[SiSGroup/Sydney, Australia]]--></description>
        <services>
            <n0>shared</n0>
            <n1>vps_solusvm</n1>
        </services>
    </n3>
</datacenters>
<execution_time>0.017 s</execution_time>
<db_time>0.010 s</db_time>
<uniq_id>8676395012</uniq_id>

现在我尝试实现一个非常简单的调用:

echo $result->ampa->datacenters->n0->name;

并收到此错误:

Trying to get property of non-object

处理这个xml我做错了什么?

BTW我的后端代码如下所示:

function index() {
    $result = $this->rest->get('/?auth_username=the-green-panda&auth_password=MacBook1&section=datacenters&command=get_datacenters');

    var_dump($result);

    echo '<hr/>';

    echo $result->ampa->datacenters->n0->name;
}

1 个答案:

答案 0 :(得分:0)

这是因为XML缺少结束</ampa>标记。

不要包含ampa。跟你一起去

$xml = simplexml_load_string($xml);
echo $xml->datacenters->n0->name;

Demo