在PHP

时间:2017-03-02 18:32:09

标签: php arrays json xml laravel

我刚创建了一个php文件来查询API中的一些数据。
正常返回的数据应该是:

{
@attributes: {
    Status: "OK"
},
Errors: { },
Warnings: { },
RequestedCommand: "checking",
CommandResponse: {
    @attributes: {
    Type: "check"
    },
    DomainCheckResult: [
        {
        @attributes: {
            Domain: "example1.com",
            Available: "true",
            ErrorNo: "0",
            Description: "",
            IsPremiumName: "false",
            PremiumRegistrationPrice: "0",
            PremiumRenewalPrice: "0",
            PremiumRestorePrice: "0",
            PremiumTransferPrice: "0",
            IcannFee: "0",
            EapFee: "0"
        }
        },
        {
        @attributes: {
            Domain: "example2.com",
            Available: "true",
            ErrorNo: "0",
            Description: "",
            IsPremiumName: "false",
            PremiumRegistrationPrice: "0",
            PremiumRenewalPrice: "0",
            PremiumRestorePrice: "0",
            PremiumTransferPrice: "0",
            IcannFee: "0",
            EapFee: "0"
        }
        },
    ]
},
Server: "asd",
GMTTimeDifference: "--5:00",
ExecutionTime: "2.622"
}

现在,当我尝试获取“Domain”和“Available”等属性值以及其他属性值将它们放入某些变量时,我会执行以下操作:

$client = new Client();
        $res = $client->request('POST', 'http://api.website.com/xml.response', [
        'form_params' => [
        'ApiUser' => 'myuser',
        'ApiKey' => 'apikey',
        'UserName' => 'myuser',
        'ClientIp' => 'myip',
        'Command' => 'check',
        'List' => $list
            ]
        ]);
        $xml = simplexml_load_string($res->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);
        $json = json_encode($xml);
        $data = json_decode($json, true);
        echo $data->CommandResponse[0];

但它告诉我:

  

尝试获取非对象的属性

我做错了什么?请帮我。谢谢。

1 个答案:

答案 0 :(得分:0)

它与json_decode函数的第二个参数有关。这告诉函数它是否应该将json字符串转换为数组或对象(请参阅PHP documentation)。在您的情况下,您创建一个数组,但希望将其作为对象访问。因此,您要么将json_decode($json, true)更改为json_decode($json),要么将echo $data->CommandResponse[0]更改为echo $data['CommandResponse'][0]

希望有所帮助!