简体   繁体   中英

How to make a JSON Curl request to an api url, getting null

This should be simple I think but I just can't fathom it.

I need to make a request to a url in the following format:

http://ratings.api.co.uk/business/ {lang}/{fhrsid}/{format} where lang will be set to en-GB the fhrsid is an identifier and format is json.

I tried the following but I am just getting null in return:

$data = array("lang" => "en-GB", "fhrsid" => "80928");                                                                    
$data_string = json_encode($data);            


$ch = curl_init('http://ratings.api.co.uk/business/json');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))                                                 );                                                                                                                   

$Jsonresult = curl_exec($ch);
curl_close($ch);

var_dump(json_decode($Jsonresult));

Any help gratefully received

You are currently posting the data to the URL, while you say you want to put the data in the URL itself.

Ie now you submit {"lang:"en-GB","fhrsid":80928} to the URL http://ratings.api.co.uk/business/json , but instead you want to retrieve the URL http://ratings.api.co.uk/business/en-GB/80928/json .

Don't use POST as request type, don't specify postfields, don't specify content-length, and do put the data in your URL.

Sending data as arguments is different than sending it within the URL.

If you require a url format of http://ratings.api.co.uk/{lang}/{fhrsid}/{format} , then you must make your curl_init string match that format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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