如何在PHP中解析POST请求并输出JSON?

时间:2017-08-03 22:02:20

标签: php json api parsing

我尝试使用JSON在rest-API中创建用户。那就是成功。

我的问题:

1)我需要从包含用户信息的webform接收POST请求吗?

2)添加APIkey并插入变量。

3)生成要发送到页面的JSON:

  

rest.domain.com/api/v1/UserCreate

来自我的WEBFORM的请求(示例)

     {
     "UserID":"11",
     "GroupID":"22",
     "MemberID":"97865454534231",
     "UserFullName":"Mr Test",
     "UserEmail":"mail@mail.com",
     "UserRegistrationNumber":"9999999",
      }

JSON CALL TO API(工作json)

    POST /api/v1/UserCreate HTTP/1.1
    Host: rest.domain.com
    APIKey: XXXXXXXXXX-XXXXXXXXX-XXXXXXXXXXX
    Content-Type: application/json

    {
    "APIKey":"XXXXXXXXXX-XXXXXXXXX-XXXXXXXXXXX",
    "UserID":"11",
    "GroupID":"22",
    "UserEmail" : "mail@mail.com",
    "UserRegistrationNumber" : "9999999",
    "UserFullName" : "Mr Test",
    "MemberID" : "123456789",
    }

1 个答案:

答案 0 :(得分:-1)

  1. 创建一个监听预定义变量中的帖子的php页面 $_POST

  2. 根据收到的数据构建一串JSON

  3. 调整标题的内容类型,echo JSON字符串     你建立了

  4. 示例:

    // CHECK POST FIELDS
    if(@$_POST['UserID'] != ''){
    
        // GENERATE API KEY
        $apiKey = ''
    
        // BUILD RESPONSE
        $jsonResponse =     '{';
        $jsonResponse .=     '"APIKey":"'.$apiKey.'",';
        $jsonResponse .=     '"UserID":"'.$_POST['UserID'].'",';
        $jsonResponse .=     '"GroupID":"'.$_POST['GroupID'].'",';
        $jsonResponse .=     '"MemberID":"'.$_POST['MemberID'].'",';
        $jsonResponse .=     '"UserFullName":"'.$_POST['UserFullName'].'",';
        $jsonResponse .=     '"UserEmail":"'.$_POST['UserEmail'].'",';
        $jsonResponse .=     '"UserRegistrationNumber":"'.$_POST['UserRegistrationNumber'].'",';
        $jsonResponse .=    '}';
    
        // SET HEADER
        header('Content-Type: application/json');
    
        // ECHO RESPONSE
        echo $jsonResponse;
    
    }