PHP变量作为URL中的参数

问题描述

| 我想创建一个天气预报器,以按访客的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\'
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...