Buddhika Priyabhashana
Buddhika Priyabhashana

Reputation: 333

When try to concatenate URL with variable it do not give expected result in php curl

I try to read XML document and convert content in to JSON using curl in php. In here i want to concatenate URL with variable.

but when add variable it retrieve null. but when i hard code text it works.

this is my code.

       $city = "paris";
       $url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%22{$city}%22)";
        print_r($url);
       // $url ="https://www.w3schools.com/xml/plant_catalog.xml";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);    // get the url contents

        $data = curl_exec($ch); // execute curl request
        curl_close($ch);

        $xml = simplexml_load_string($data);
        echo json_encode($xml);

this is my url

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%22{$city}%22)

It works when i add "paris" rather than {$city}

please help me to sortout this problem.

Upvotes: 0

Views: 426

Answers (2)

Buddhika Priyabhashana
Buddhika Priyabhashana

Reputation: 333

In here there is another problem. URL concatenate correctly with variable.

But the thing is i take value to variable via POST method. when send test via POST method it contains new line at last. becouse of that when i add variable to urs it devided to 2 parts.

I solved it by "trim" method.

$city = trim(preg_replace('/\s\s+/', ' ', $_REQUEST['city']));

When use like that it worked.

Upvotes: 0

Nawin
Nawin

Reputation: 1692

You need to decode the url and concatenate and encode the url like :

$city = "paris";
$url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%22{$city}%22)";
$url1 = urldecode($url);
print_r(urlencode($url1));

By the way i test your code in my localhost it shows me correct output screen shot is: enter image description here

Upvotes: 1

Related Questions