问题描述
|
我想创建一个天气预报器,以按访客的IP显示天气预报。
我正在尝试将变量$ ip放置到URL中,但是它不起作用。当我放置真实IP而不是$ ip时。有用。
我究竟做错了什么?
$ip=$_SERVER[\'REMOTE_ADDR\'];
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,\"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=.$ip.&localObsTime&num_of_days=5&format=json\");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
$outputJson = curl_exec($ch);
if ($outputJson === FALSE) {
echo \'Error: \'.curl_error($ch);
}
echo \'<pre> \';
print_r($outputJson);
echo \'</pre> \';
解决方法
$ip
之前和之后有一些不必要的点:
使用以下任何一项:
\"http://...$ip...\"
\"http://...{$ip}...\"
\"http://...\" . $ip . \"...\";
, 尝试做
curl_setopt($ch,CURLOPT_URL,\"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=\".$ip.\"&localObsTime&num_of_days=5&format=json\");
, 您不需要连接字符串,因为您使用的是双引号。所以你要么做:
curl_setopt($ch,\"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=$ip&localObsTime&num_of_days=5&format=json\");
在网址中。
, 您正在字符串中使用字符串连接运算符。要么使用
\"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=$ip&localObsTime&num_of_days=5&format=json\"
要么
\'http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=\'.$ip.\'&localObsTime&num_of_days=5&format=json\'