PHP curl request

I am running a script with a curl GET request but my code is not currently outputting anything. Here is the code, I think that I need to add the parameters to the url but need some direction as how to do that?

Here is the code;

<?php
$curl = curl_init();

// Array Parameter Data
$data = [
  'lat'=>'52.509120', 
  'lon'=>'-1.884915',
  ];

curl_setopt_array($curl, [
  CURLOPT_URL => "https://geo.fcc.gov/api/census/area",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_HTTPHEADER => [
    "Content-Type: application/json",
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);


if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

I have the solution -

CURLOPT_POSTFIELDS is only for doing POST requests. For GET you just include the parameters in the URL’s query string. You do that by adding a ? followed by the parameters in name=value&name=value2 format with proper url encoding applied.

PHP has a function to build the appropriate string from an array of parameters: http_build_query. Use that and concatenate the result to the URL.

remove: CURLOPT_POSTFIELDS.

edit: CURLOPT_URL => "https://geo.fcc.gov/api/census/area?".http_build_query($data)

*Thanks to kicken in phpfreaks forum.

Sponsor our Newsletter | Privacy Policy | Terms of Service