PHP Using cURL and GET Requests in a URL

I use cURL instead of file_get_contents, which works fine on the URL until I used the GET request variable instead of the city at the URL below.

Using cURL for the following: (Works)

$url = 'http://www.weather-forecast.com/locations/London/forecasts/latest';

This works great, however, if we substitute "London" with a variable $city:

URL: example.com/weather.php?city=London

$city = $_GET['city'];
$city = ucwords($city); 
$city = str_replace(" ", "", $city);

$url = 'http://www.weather-forecast.com/locations/".$city."/forecasts/latest';

I get an error message: The page you are looking for doesn't exist (404)

What am I doing wrong in my cURL function? This seems to work fine with file_get_contents, is there something I can't see?

cURL function

function curl_get_contents($url)
{
$ch = curl_init();
$timeout = 5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$data = curl_exec($ch);

curl_close($ch);

return $data;
}

$contents = curl_get_contents($url);
echo $contents;
+4
source share
1 answer

Please replace the double quotes with single quotes in the url,

$url = 'http://www.weather-forecast.com/locations/'.$city.'/forecasts/latest';
0
source

All Articles