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

2

3 Answers 3

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.

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'];
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.