简体   繁体   English

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

[英]Post data and retrieve the response using PHP Curl?

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 -Elliot

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变量中提供。

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

The default behavior of Curl is to just dump the data you get back out to the browser. Curl的默认行为是将您返回的数据转储到浏览器中。 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. 您还可以在此$ txResult上使用parse_string来正确格式化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM