简体   繁体   English

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

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

I have a CURL response that looks like this: 我有一个CURL响应,如下所示:

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

All i need from that is the value of "total_results":0 我需要的是"total_results":0的值"total_results":0

so I am trying to get "total_results" like this: 所以我试图得到这样的"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];

However, when I echo the $output->total_results[0]; 但是,当我回显$output->total_results[0]; , I get nothing being echoed on my page. ,我的页面上没有任何回声。 So i don't really know what I am doing wrong! 所以我真的不知道我在做什么错!

Could someone please advise on this issue? 有人可以建议这个问题吗?

any help would be appreciated. 任何帮助,将不胜感激。

What you got as a response is a JSON string. 作为响应,您得到的是JSON字符串。 You can parse it to a stdClass object using json_decode : 您可以使用json_decode将其解析为stdClass对象:

$object = json_decode( $output );

Then you can access the field you want: 然后,您可以访问所需的字段:

$total_results = $object->total_results;

Alternatively, you can parse the JSON string to an array: 另外,您可以将JSON字符串解析为数组:

$array = json_decode( $output, true );

and get the var: 并获取var:

$total_results = $array['total_results'];

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

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