1

I can get the JSON file from a weather site, knowing latitude and longitude of a location with this code:

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,'https://weathersite.xyz/complete.json?lat=39&lon=-8');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
 $fIOURL = curl_exec($ch);
 curl_close($ch) ;

It works fine, and I get the JSON for that latitude and longitude. Now I want to replace the numeric value of latitude by the corresponding php variable, something like:

 $latitude = "39";

However, when I replace the numeric value by this variable, it stops working and I can't get the JSON anymore.

I tried

 curl_setopt($ch, CURLOPT_URL,'https://weathersite.xyz/complete.json?lat={$latitude}&lon=-8');

or

 curl_setopt($ch, CURLOPT_URL,'https://weathersite.xyz/complete.json?lat=".$latitude."&lon=-8');

What am I doing wrong?

  • 1
    It's a simple matter of double quoting our URL instead of single quoting. Variables are not interpolated in the single quotes, and your second attempt you closed a single quoted string with doubles to concatenate. You can just use `"https://weathersite.xyz/complete.json?lat={$latitude}&lon=-8"` or `'https://weathersite.xyz/complete.json?lat=' . $latitude . '&lon=-8'` - you just have to balance your quotes correctly. – Michael Berkowski Jun 28 '21 at 00:50

0 Answers0