【发布时间】:2019-04-13 20:12:07
【问题描述】:
我被 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]);
刚刚得到错误:类 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) 我正在寻找在“结果”数组下获取信息的方法 键:值格式如:
$VatId = $value['businessId'];
$Name = $value{'name'];
$RegDate = $value['registrationDate'];
$companyForm = $value['companyForm'];
等等,以便能够保存它们。
到目前为止响应的输出:
"results": // <- IN this part has company information
[{"businessId":"0856064-3",
"name":"Company Ltd",
"registrationDate":"1991-09-18",
"companyForm":"Ltd",
感谢 MikroMike
【问题讨论】: