【问题标题】:How to save data json from api external to database in laravel如何将来自api外部的数据json保存到laravel中的数据库
【发布时间】:2019-12-13 13:03:53
【问题描述】:

我想使用 guzzle 从 api 外部生成报告,这是我的结果

{#430 ▼


+"data": {#427 ▼
    +"report_id": "20190801-5f6e21a5"
    +"status": 5
    +"creation_date": "2019-08-01 13:19:49"
    +"due_date": "2019-08-02 13:19:49"
    +"data": {#432 ▼
      +"chassis_number": "ACR50-0183692"
      +"engine": "2AZFE"
      +"manufacture_date": "2014-07"
      +"registration_date": "2019-04-17"
      +"make": "TOYOTA"
      +"model": "ESTIMA"
      +"displacement": "2360"
      +"fuel": "GASOLINE"
    }
  }
  +"error": ""
}

但我不知道如何从这个 json 中获取值并保存到数据库。我想保存来自 report_id、状态、创建日期等的值

$client = new Client();
        $body = $client->request('GET', 'https://xxxxx/api/v1/get-report', [
        'headers' => [
            'Accept'     => 'application/json',
            'Carvx-User-Uid' => 'xxxxxx', 
            'Carvx-Api-Key' => 'xxxxxx',
            'needSignature' => '0', 
            'raiseExceptions' => '1',
            'isTest' => '0'
        ],
            'query' => [
                'report_id' => $reportId,
                'true'=>'1'
            ]
    ])->getBody();

    $contents = (string) $body;
    $data = json_decode($contents);
   // dd($data);
    
    //to get value from status 

    $var_status =  var_export($data['status'],true);
    $status = substr($var_status, 1, -1); 
    echo $status;

我得到了这个错误

不能将 stdClass 类型的对象用作数组

【问题讨论】:

    标签: json laravel guzzle


    【解决方案1】:

    json_decode 默认返回一个Stdclass 对象,其属性表示 json 对象中的键。

    你可以告诉json_decode返回一个关联数组,而不是通过传递true作为第二个参数:

    json_decode($contents, true); // returns array
    

    文档:https://www.php.net/manual/en/function.json-decode.php

    【讨论】:

    • 如何只回显 STATUS 值? $var_status = var_export($data['status'],true); $status = substr($var_status, 1, -1);回声$状态;还是错误
    猜你喜欢
    • 2016-12-13
    • 2021-06-10
    • 1970-01-01
    • 2020-01-15
    • 2020-06-09
    • 2020-02-21
    • 2018-03-04
    • 1970-01-01
    • 2012-12-31
    相关资源
    最近更新 更多