我坚持使用JSON。
我可以使用Guzzle通过API GET响应接收数据。
我正在尝试使用Laravel 5.7将数据提取为key:value格式, 可以将其保存为版本5.55的mysql db(不了解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
答案 0 :(得分: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
}