Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post data and retrieve the response using PHP Curl?

I'm very new to working with web services, and so I'm finding this pretty confusing.

If I have a URL I'm trying to post some JSON data to, I understand how to do this using the CURL PHP method.

What I'm wondering is, if I do this, and the URL has some kind of server response.. how do I get that response in my php and use it to take different actions within the PHP accordingly?

Thanks!

-Elliot

like image 847
Elliot Avatar asked Feb 09 '11 15:02

Elliot


People also ask

What does PHP cURL return?

Functions of cURL in PHP curl_error — It will return the string which represents the error for the particular current session.

How does PHP handle cURL response?

Just use the below piece of code to get the response from restful web service url, I use social mention url. Oldie bug a goodie... +1 for using curl_setopt_array(). So much cleaner than calling curl_setopt() over and over.

How post cURL JSON PHP?

Send JSON data via POST with PHP cURLSpecify the URL ( $url ) where the JSON data to be sent. Initiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.


1 Answers

You'll have to set the CURLOPT_RETURNTRANSFER option to true.

$ch = curl_init($url);  curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch);  curl_close($ch); 

The response to your request will be available in the $result variable.

like image 53
András Szepesházi Avatar answered Sep 30 '22 07:09

András Szepesházi