简体   繁体   中英

curl how to format a curl request with an api key in php

hi am new to curl but need it for a particular project could you help me format this code to work i would like to get the results and print out the raw JSON on the page here is the code i am using

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "curl -u api key: https://api.companieshouse.gov.uk/search/companies");
$x = curl_exec($curl);
curl_close($curl);
print($x);

this is a link to the api page i am trying to use https://developer.companieshouse.gov.uk/api/docs/search/companies/companysearch.html

this is the example they give on the page

curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: 
https://api.companieshouse.gov.uk/search/companies

these are the parameters for the call if possible i would like to set them as well

q (required)
items_per_page (optional)
start_index (optional)

I simplified your request.you can try this by using below code.

$params = array("q"=>"<Some Value>","items_per_page"=>"<Some Value>","start_index"=>"<Some Value>");

$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "api key:");
curl_setopt($curl, CURLOPT_URL, "https://api.companieshouse.gov.uk/search/companies?".http_build_query($params));
$x = curl_exec($curl);
curl_close($curl);
print($x);

Thanks for this opportunity to learn more of curl :-)

I tested the code below, it works. Of course you must be registered on the site and you must have got your API key. You will then provide it as username/password, but without username (this is written here on the site ).

$searchvalue= 'Test';

$curl = curl_init("https://api.companieshouse.gov.uk/search/companies?q=$searchvalue");

curl_setopt($curl, CURLOPT_USERPWD, "your_api_key_provided_by_the_site");

// curl_setopt($curl, CURLOPT_HEADER, true); // when debugging : to show returning header

$rest = @curl_exec($curl);
print_r($rest);

if(curl_errno($curl))
{
    echo 'Curl error : ' . curl_error($curl);
}

@curl_close($curl);

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