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
  • 1
    Can you show some of the code you have right now? Commented Feb 9, 2011 at 15:41
  • This answer here worked for me https://stackoverflow.com/a/34933064/4601322 Commented May 29, 2020 at 16:25

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.