【问题标题】:Trying to get property 'data' of non-object when fetching data using CURL in Laravel在 Laravel 中使用 CURL 获取数据时尝试获取非对象的属性“数据”
【发布时间】:2018-10-11 06:48:30
【问题描述】:

我正在构建一个 Laravel 应用程序,我使用 CURL 从外部 API 获取数据并填充我的网页。应该执行 GET 请求的 Curl 函数最初运行良好,但我今天尝试过,它抛出了一个错误

(1/1) ErrorException Trying to get property 'data' of non-object

很难调试。错误所指的数据是下面所示的旅行函数中的第一行代码。

请帮忙?

我的控制器代码

   public
    function travel()
    {

 
        $cover_options = $this->global_Curl_get('api/travel/cover-options')->data;
        $countries = $this->global_Curl_get('api/general/countries')->data;
        return view('B2C::travel.travel')->with(['coveroptions' => $cover_options, 'countries' => $countries]);
    }

global_Curl_get 函数

 public function global_Curl_get($url)
    {
        //dd($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url);
        $ch = curl_init();
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => ($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url),
        ));
        // Send the request & save response to $resp
        $response = json_decode(curl_exec($ch));

        curl_close($ch);
        return $response;
    }

【问题讨论】:

  • 如果您收到关于 非对象 的错误,则表示 Curl 调用未返回有效的 JSON。检查curl_exec 调用的结果,您会发现发生了什么。
  • @iainn 谢谢问题是第三方 API 端点没有推送任何数据

标签: php laravel curl error-handling


【解决方案1】:

也许您的函数正在返回一个数据数组。 你可以试试这样的。

function travel()
 {
    $cover_options = $this->global_Curl_get('api/travel/cover-options');

    $countries = $this->global_Curl_get('api/general/countries');
    return view('B2C::travel.travel')->with(['coveroptions' => $cover_options['data'], 'countries' => $countries['data']]);
}

【讨论】:

  • 你能提供一个$cover_options的vardump吗,可能是json_encoded数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2015-09-22
  • 2015-04-28
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多