PHP에서 json post 를 처리하는 방법.

How to Handle JSon POST Request Using PHP


http://edwin.baculsoft.com/2011/12/how-to-handle-json-post-request-using-php/


On my last project, i need to create a php service using JSon to handle service requests from multiple clients. My PHP file would consume JSon string for its requests and produce JSon string as its responses.
Im not too familiar with PHP, but after sometime googling i’ve found a workaround. This is how i do it.

01<?php
02// JSon request format is :
03// {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}
04 
05// read JSon input
06$data_back = json_decode(file_get_contents('php://input'));
07 
08// set json string to php variables
09$userName = $data_back->{"userName"};
10$password = $data_back->{"password"};
11$emailProvider = $data_back->{"emailProvider"};
12 
13// create json response
14$responses = array();
15for ($i = 0; $i < 10; $i++) {
16    $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
17}
18 
19// JSon response format is :
20// [{"name":"eeee","email":"eee@zzzzz.com"},
21// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]
22 
23// set header as json
24header("Content-type: application/json");
25 
26// send response
27echo json_encode($responses);
28?>

This is the http header and body of request and response.

Hope it help others, have fun with JSon


지난글에서 C# 으로 post json 데이터를 날리는 경우에는

Content-Type 가 

application/x-www-form-urlencoded 

인 경우에는 $_POST[postData] 로 받아서 처리하면 되는데.


Content-Type 자체가 

application/json

인 경우에는 php 에서 위와 같이 처리한다.