【问题标题】:Api in PHP - Accept a curl request and processPHP 中的 Api - 接受 curl 请求并处理
【发布时间】:2012-12-10 20:06:32
【问题描述】:

不确定是否有人可以帮助我解决问题。

我必须为我工作的公司编写一些 php,以便我们与接受 JSON 主体的 API 集成。我使用了 cUrl 方法,脚本运行良好。

如果我想构建另一个可以接受我发送的请求的 php 页面,我该怎么做?

假设我想让某人向我发送相同的请求,然后希望他们发送的信息进入我的数据库,如何将他们的请求转换为 php 字符串?

这是我发送的代码。

<?
$json_string = json_encode(array("FirstName" => $name, "MiddleName" => " ", "LastName" => $last));;
// echo $json_string;
// jSON URL which should be requested
$json_url = 'http://www.exampleurl.com';
// jSON String for request
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
    'Accept: application/json;charset=utf-8',
    'Content-Type: application/json;charset=utf-8',
    'Expect: 100-continue',
    'Connection: Keep-Alive') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result =  curl_exec($ch); // Getting jSON result string
echo $result;
$myArray = json_decode($result);
$action = $myArray->Action;
?>

【问题讨论】:

  • 还有什么问题?只需在 $_POST 数组中查找 json_string。
  • @Hast 看起来不像是在使用 $_POST 数组,而是在使用 JSON。在这种情况下,他将不得不从 POST 正文中获取原始数据和/或从该正文中寻找他想要的单个 JSON 对象以获得他需要的内容。他可以做一个 http 查询格式的版本,但我不相信这是示例显示的内容。

标签: php api curl


【解决方案1】:

要从您将收到的 POST 中获取原始数据,您可以使用 $postData = file_get_contents('php://input');

http://php.net/manual/en/reserved.variables.post.php

然后你会 json_decode() 将该 POST 的内容返回到 JSON。

http://php.net/manual/en/function.json-decode.php

【讨论】:

    【解决方案2】:

    不太了解您的问题。可能您正在寻找读取原始 POST 数据的方法?在这种情况下打开并从php://stdin 流中读取。

    $stdin = fopen('php://stdin', 'r');
    

    顺便阅读这里(http://php.net/manual/en/function.curl-setopt.php)如何使用CURLOPT_POSTFIELDS。此参数可以作为 urlencoded 字符串(例如 'para1=val1&para2=val2&...')传递,也可以作为以字段名称为键、字段数据为值的数组传递。

    【讨论】:

    • CURLOPT_POSTFIELDS 不必是 key-value 字符串,只要正确地进行 URL 编码即可!
    • 我明白这一点。引用文档的含义是 OP 正在滥用它。但是,在 OP 中的使用是完全可以接受的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 2017-01-21
    相关资源
    最近更新 更多