want to send and receive json data in php
json, php
Solution
Modify your function to send header of JSON_DATA in post request
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
In file use
<?php
$json_input_data=json_decode(file_get_contents('php://input'),TRUE);
print_r( $json_input_data);
?>
As everyone said there is no need of `$str_data = json_encode($data);`,Since data is already in json.
Problem
As per application requirement, I am trying to develop two PHP which can communicate with each other via Json. I tried searching online but didn't found solution. Can any one suggest me the right path for this? I have data in mysql database, the converted data will be in json format as given below: (Also looking for code to get this data format via PHP-JSON object and array.) ``` { "user" : [ { "firstName" : "Vignesh", "lastName" : "Prajapati", "age" : 23, "email" : ["vignesh@gmail.com","vignesh@yahoo.com"], "subject" : ["English","Gujarati", "Hindi"] }, { "firstName" : "Vaibhav", "lastName" : "Prajapati", "age" : 19, "email" : ["vaibhav@gmail.com","vaibhav@yahoo.com","vaibhav@aol.com"], "subject" : ["English","Spanish", "Chinese","Sanskrit"] } ] } ``` My Php code for sending Json data: (send.php) ``` <?php $data = ' { "user" : [ { "firstName" : "Vignesh", "lastName" : "Prajapati", "age" : 23, "email" : ["vignesh@gmail.com","vignesh@yahoo.com"], "subject" : ["English","Gujarati", "Hindi"] }, { "firstName" : "Vaibhav", "lastName" : "Prajapati", "age" : 19, "email" : ["vaibhav@gmail.com","vaibhav@yahoo.com","vaibhav@aol.com"], "subject" : ["English","Spanish", "Chinese","Sanskrit"] } ] } '; $url_send ="http://localhost/rec.php"; $str_data = json_encode($data); function sendPostData($url, $post){ $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS,$post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $result = curl_exec($ch); curl_close($ch); // Seems like good practice return $result; } echo " " . sendPostData($url_send, $str_data); ?> ``` My Php code for receiving Json data: (rec.php) ``` <?php $json_input_data=json_decode(file_get_contents('php://input'),TRUE); echo $json_input_data; ?> ```