PHP API 在 POST 中获取空的 JSON 请求

标签 php json api curl

<分区>

我正在尝试在 php 中开发小型 API 代码,它将使用 PHP curl(从客户端)以 json 格式发送 POST 请求。在接收端(在服务器端)我想解析请求并处理它。但在接收方,它在 post 字段中给了我空数组。 下面是我的代码

客户端:

<?php

    $data = array("name" => "Hagrid", "age" => "36");                                                                    
    $data_string = json_encode($data);                                                                                   
    $ch = curl_init($url);                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, "xdata=".$data_string);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   
    echo $result = curl_exec($ch);

?>

在服务器端:

<?php

    print_r($_POST);

?>

Blockquote Array ( ) Blockquote

它总是在服务器端给我空的 POST 数组。 我做错了什么还是有另一种方法来解析请求? 请指导我。

最佳答案

您可以使用php://input 只读流来访问JSON post 数据,而不是像这样$_POST

<?php 
    $json = file_get_contents('php://input');
?>

它将按原样为您提供 POST 数据。稍后您将能够使用 json_decode() 对其进行解码。

示例代码-

<?php 
   $json = json_decode(file_get_contents('php://input'));
?>

关于PHP API 在 POST 中获取空的 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35474089/

相关文章:

php - 使用 pchart 和 mysql 创建图表 - 提供的示例中的正确语法

php - 意外 token '<' - AJAX

Python - 在字典列表中查找重复项并将它们分组

node.js - 如何在 Snapdeal 上生成 X-Auth-Token 和 X-Seller-AuthZ-Token

Laravel 的时间戳有奇怪的返回格式

php - 反向代理背后的 Oauth 提供者

php - Netbeans,xdebug : start debugging from browser

PHP/MySQL 检查值是否存在,如果存在则不插入

api - 如何通过命令行在GitHub上发布版本?

javascript - Angular JS,是否可以动态设置 ng-include 或 ng-controller?