繁体   English   中英

PHP:如何从API调用解析JSON?

[英]PHP: How to Parse JSON From API call?

我有一个CURL响应,如下所示:

{"page_number":2,"items":[],"items_per_page":1,"kind":"search#companies","total_results":0,"start_index":1} 

我需要的是"total_results":0的值"total_results":0

所以我试图得到这样的"total_results"

$url = "https://api.companieshouse.gov.uk/search/companies?q=POOdfgdfgyygfhfgfgfghgfP&items_per_page=1&start_index=0";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "my_password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

$output = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$info = curl_getinfo($ch);
curl_close($ch);

echo $output->total_results[0];

但是,当我回显$output->total_results[0]; ,我的页面上没有任何回声。 所以我真的不知道我在做什么错!

有人可以建议这个问题吗?

任何帮助,将不胜感激。

作为响应,您得到的是JSON字符串。 您可以使用json_decode将其解析为stdClass对象:

$object = json_decode( $output );

然后,您可以访问所需的字段:

$total_results = $object->total_results;

另外,您可以将JSON字符串解析为数组:

$array = json_decode( $output, true );

并获取var:

$total_results = $array['total_results'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM