json_encode($ response);如何处理Json API,用Laravel提取json格式

问题描述 投票:0回答:1

我坚持使用JSON。

我可以通过使用Guzzle通过API GET响应接收数据。

我正在尝试使用Laravel 5.7将数据提取到key:value格式,以便能够保存mysql db,这是版本5.55(不了解JSON格式)

并使用Blade处理它能够向最终用户显示它。

 use GuzzleHttp\Psr7\Response;

///获得响应///

  $data = json_decode( (string) $response->getBody() );
  echo $response->getBody() ; 

JSON响应格式为:

{
  "type": "fi.prh.opendata.bis",
  "version": "1",
  "totalResults": -1,
  "resultsFrom": 0,
  "previousResultsUri": null,
  "nextResultsUri": null,
  "exceptionNoticeUri": null,
  "results": [ // <- IN this part has company information
    {
      "businessId": "0856064-3",
      "name": "Company Ltd",
      "registrationDate": "1991-09-18",
      "companyForm": "Ltd",
      "detailsUri": null,
      "liquidations": [

      ],
      "names": [ // <- other array, which has history of Company names
        {
          "order": 0,
          "version": 1,
          "name": "Company Ltd",
          "registrationDate": "1991-08-14",
          "endDate": null,
          "source": 1
        }
      ]
    }
  ]
}

1)试图从数组中提取公司信息“结果”:

echo $response->getBody()->getContents([results]); 

刚刚获得ERROR:Class App \ PRHData不存在,它与拥有代码的文件相同。

2)试图从数组中提取公司信息“结果”:

 foreach($data[result[0]]['businessId'] as $i => $v)
 {
 echo $v['businessId'].'<br/>';
 }

我收到错误:

 Use of undefined constant result - assumed 'result' (this will 
 throw an Error in a future version of PHP)

我不知道那个错误信息是什么。


use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request as GuzzleRequest;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7;

class PRHData extends Model
{
public static function getJson()
{

///发送请求///这部分有效,我通过API获取数据。

$client = new Client([
   'base_uri' => 'https://avoindata.prh.fi/bis/v1/',
   'defaults'=>[
     'timeout'  => 2.0,
     'cookies' => true,
     'headers'  => ['content-type' => 'application/json']]
  ]);
  $response = $client->request('GET','0856064-3'); //<- number is 
                             parameter for GET request to API call

///结束发送请求///

///获得响应///

 $data = json_decode( (string) $response->getBody() ); // WORKS! 
 echo $response->getBody() ;   // Works !!!!

1)我正在寻找将“result”数组下的信息获取到key:value格式的方法,如:

$VatId = $value['businessId'];
$Name = $value{'name'];
$RegDate = $value['registrationDate'];
$companyForm = $value['companyForm'];

等等,能够保存他们db。

到目前为止的回复输出:

"results": // <- IN this part has company information

[{"businessId":"0856064-3",

"name":"Company Ltd",

"registrationDate":"1991-09-18",

"companyForm":"Ltd",

谢谢Micro

php json laravel-5 guzzle
1个回答
0
投票

您可以使用json_decode的结果访问它,它将JSON解析为PHP对象/数组:

//...
$data = json_decode( (string) $response->getBody() );

$VatId = $data->results[0]->businessId;

请注意,这只会访问索引为0的第一家公司。您可以使用foreach循环遍历每个结果:

//...
$data = json_decode( (string) $response->getBody() );

foreach ($data->results as $company) {
    $VatId = $company->businessId;
    // Do something with it in the iteration
}
© www.soinside.com 2019 - 2024. All rights reserved.