使用 PHP Curl 发布数据并检索响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4947025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:19:47  来源:igfitidea点击:

Post data and retrieve the response using PHP Curl?

phppostcurlwebservice-client

提问by Elliot

I'm very new to working with web services, and so I'm finding this pretty confusing.

我对使用 Web 服务非常陌生,所以我发现这很令人困惑。

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.

如果我有一个 URL,我想将一些 JSON 数据发布到,我知道如何使用 CURL PHP 方法来做到这一点。

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?

我想知道的是,如果我这样做,并且 URL 有某种服务器响应..如何在我的 php 中获得该响应并使用它在 PHP 中相应地采取不同的操作?

Thanks!

谢谢!

-Elliot

-艾略特

回答by András Szepesházi

You'll have to set the CURLOPT_RETURNTRANSFER option to true.

您必须将 CURLOPT_RETURNTRANSFER 选项设置为 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.

对您的请求的响应将在 $result 变量中可用。

回答by dmcnelis

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

如果您指的是针对不同 HTTP 响应代码的不同操作,那么您可以执行以下操作:

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

$httpResponseCode = $responseInfo['http_code'];

回答by ayush

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 的默认行为只是将您获得的数据转储到浏览器。为了将其捕获到变量中,您需要:

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

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

你也可以在这个 $ txResult上使用parse_string来正确格式化它。