简体   繁体   中英

PHP Using cURL and GET request in URL

I am using cURL instead of file_get_contents, which is working fine on the URL until I used a GET request variable in place of the city on the URL below.

Using cURL on the following: (Works)

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

This works fine, however when substituting '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: The page you are looking for doesn't exist (404)

What am I doing wrong in my cURL function? This seems to work perfectly with file_get_contents , is there something I am missing?

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;

请用url中的单引号替换双引号,

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

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