【问题标题】:PHP Variable as a parameter in the URLPHP 变量作为 URL 中的参数
【发布时间】:2011-09-22 14:14:57
【问题描述】:


我想创建按访问者 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> ';  

【问题讨论】:

  • 当你做 print_r 你至少有正确的输出吗?
  • @Tarek 是的,它返回 json 数据(如果 IP 是真实的,而不是变量)

标签: php api url variables parameters


【解决方案1】:

$ip前后有一些不必要的点:

使用以下任何一种:

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

【讨论】:

    【解决方案2】:

    尝试做

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

    【讨论】:

    • 因为双引号没有作用。
    【解决方案3】:

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

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

    在网址中。

    【讨论】:

      【解决方案4】:

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

      "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'
      

      【讨论】:

        猜你喜欢
        • 2011-05-12
        • 2018-04-17
        • 2019-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多