PHP 变量作为 URL 中的参数

问题描述 投票:0回答:4

我想创建天气通知程序,通过访问者的 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> ';  
php url parameters
4个回答
2
投票

前后有一些不必要的点

$ip
:

使用以下任意一项:

"http://...$ip..."
"http://...{$ip}..."
"http://..." . $ip . "...";

1
投票

尝试做

curl_setopt($ch, CURLOPT_URL, "http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=".$ip."&localObsTime&num_of_days=5&format=json");

1
投票

您不需要连接字符串,因为您使用的是双引号。所以你要么这样做:

curl_setopt($ch, CURLOPT_URL, "http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=$ip&localObsTime&num_of_days=5&format=json");

在网址中。


0
投票

您正在字符串内使用字符串连接运算符。要么使用

"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'
© www.soinside.com 2019 - 2024. All rights reserved.