首页 > 解决方案 > 无法从 web 服务的返回代码中获取值

问题描述

当我使用系统的休息 API 时,我无法将特定“字段”的值返回到 PHP 中。错误消息说:

注意:试图获取非对象的属性。

$response = file_get_contents('https:/....');
echo $response->Ticket['Owner'];
echo $response->Ticket->Owner;
echo $response['Owner'];
{"Ticket":[{"Owner":"root@localhost","EscalationTime":0,"Age":17628,"ChangeBy":7}]}"

是我得到回报的一部分。现在我想将例如“所有者”存储到一个 php 变量中......

但是使用$response->Owner$response->Ticket->Owner

我得到了非对象错误的属性

标签: phparraysjson

解决方案


看看这个:

$obj = '{"Ticket":[{"Owner":"root@localhost","EscalationTime":0,"Age":17628,"ChangeBy":7}]}';  
// This is what you get from your rest API

$arr = json_decode($obj);  // decode the JSON string

print_r($arr);

输出将是:

stdClass Object
(
    [Ticket] => Array
        (
            [0] => stdClass Object
                (
                    [Owner] => root@localhost
                    [EscalationTime] => 0
                    [Age] => 17628
                    [ChangeBy] => 7
                )

        )

)

因此,您可以访问以下数据:

echo $arr->Ticket[0]->Owner;

输出将是: root@localhost

php小提琴


推荐阅读