Post data and retrieve the response using PHP Curl?

限于喜欢 提交于 2019-11-27 13:31:30

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.

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

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.

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