Vera
Vera

Reputation: 105

PHP Variable as a parameter in the URL

I want to create weather informer that shows weather forecast by visitor's IP.

I'm trying to place variable $ip to the URL but it doesn't work. When I place real IP instead of .$ip. it works.

What am I doing wrong?

$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> ';  

Upvotes: 1

Views: 808

Answers (4)

Mina
Mina

Reputation: 737

you don't need to concatenate the string since you're using doublequotes. so you either do:

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

in the url.

Upvotes: 1

knittl
knittl

Reputation: 265155

you are using the string concatenation operator inside the string. either use

"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q=$ip&localObsTime&num_of_days=5&format=json"

or

'http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxxxx&q='.$ip.'&localObsTime&num_of_days=5&format=json'

Upvotes: 0

Crozin
Crozin

Reputation: 44376

You have got some unnecessary dots before and after $ip:

Use any of following:

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

Upvotes: 2

donk
donk

Reputation: 1570

Try doing

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

Upvotes: 1

Related Questions