Post data and retrieve the response using PHP Curl?
Asked Answered
V

3

27

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

Vaasa answered 9/2, 2011 at 15:37 Comment(2)
Can you show some of the code you have right now?Oersted
This answer here worked for me https://mcmap.net/q/505332/-how-to-return-data-using-curl-callJowl
C
59

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.

Childs answered 9/2, 2011 at 15:44 Comment(0)
D
8

If you are referring to different actions for different HTTP response codes, then you can do something like:

$response = curl_exec($req);
$responseInfo = curl_getinfo($req);

$httpResponseCode = $responseInfo['http_code'];
Decentralize answered 9/2, 2011 at 15:47 Comment(0)
S
6

The default behavior of Curl is to just dump the data you get back out to the browser. In order to instead capture it to a variable, you need:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$txResult = curl_exec($ch);

Also you can use parse_string on this $txResult to properly format it.

Subjectivism answered 9/2, 2011 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.