想要在php中发送和接收json数据 [英] want to send and receive json data in php
问题描述
根据应用程序需求,我正在尝试开发两个可以通过Json相互通信的PHP.我尝试在线搜索,但未找到解决方案.
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?
我在mysql数据库中有数据,转换后的数据将为json格式,如下所示:(还寻找通过PHP-JSON对象和数组获取此数据格式的代码.)
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"]
}
]
}
我用于发送Json数据的Php代码:(send.php)
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);
?>
我用于接收Json数据的Php代码:(rec.php)
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;
?>
推荐答案
修改您的函数以在发布请求中发送JSON_DATA的标头
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;
}
在文件中使用
<?php
$json_input_data=json_decode(file_get_contents('php://input'),TRUE);
print_r( $json_input_data);
?>
每个人都说不需要$str_data = json_encode($data);
,因为数据已经在json中了.
As everyone said there is no need of $str_data = json_encode($data);
,Since data is already in json.
这篇关于想要在php中发送和接收json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!