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.
<?php
// JSon request format is :
// {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}
// read JSon input
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$userName = $data_back->{"userName"};
$password = $data_back->{"password"};
$emailProvider = $data_back->{"emailProvider"};
// create json response
$responses = array();
for ($i = 0; $i < 10; $i++) {
$responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
}
// JSon response format is :
// [{"name":"eeee","email":"eee@zzzzz.com"},
// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]
// set header as json
header("Content-type: application/json");
// send response
echo json_encode($responses);
?>
This is the http header and body of request and response.

Hope it help others, have fun with JSon. 😉
Really really useful. Cheers and good luck in life.
Hi, thatdude.
Glad it can helped you 🙂
i’m beginner in POST Request Using PHP. can you post step by step how you pass the parameter into this Service.
Hi star,
you could use CURL to simulate POST using PHP
$curl = curl_init($url);curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_exec($curl);
Hi Edwin,
what is the value of $content? An array of JSON like the example above? like this {“userName”:”654321@zzzz.com”,”password”:”12345″,”emailProvider”:”zzzz”}.
Thanks 😀 (Y)
Hi Star,
$content would be the json_encode of your array,
perhaps something like this
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('userName'=>$userName,'password'=>$password)));sorry for the previous incomplete example 🙂
Hello Edwin,
I tried running your code and this is what it gave;
Parse error: syntax error, unexpected ‘:’ in line 3,
Is there any fix?
Hi Felix, i dont know whats your json request is, so i cant tell whats wrong 🙁
Thank you so much for sharing this Edwin, you solved a problem for me today! 🙂
Hi, Thanks for sharing this such a handful easy to use snippet. Keep sharing, good luck
I have used your code but I am still getting NULL response after json_decode. Please help me its urgent. If you want I can send you the code I am using.
Been looking for a solution for ages. Think it is the format i have on my json or something, finally this solved it. Appreciate you putting this up, good man!
Thanks !