Post data and retrieve the response using PHP Curl?

对着背影说爱祢 提交于 2019-11-26 16:22:50

问题


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


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/4947025/post-data-and-retrieve-the-response-using-php-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!