从移动应用程序检索PHP上的json数据 [英] Retrieving json data on PHP from mobile app
问题描述
我很难从移动应用程序发送的发布请求中获取JSON
数据字段.
I am having a hard time trying to get the JSON
data fields, out of the post request sent from a mobile application.
在客户端(移动应用程序)上,可以使用模型类轻松地对JSON
数据进行编码.
On the client (mobile app) the JSON
data is easily encoded using the model class.
Future<http.Response> postRequest(CustomerData data) async {
var url = 'http://xxxxxxxxxxxx/testSendData.php';
var body = data.toJson();
var response = await http.post(url, headers: {"Content-Type": "application/json"}, body: body);
print("RESPONSE STATUS : ${response.statusCode}");
print("RESPONSE BODY : ${response.body}");
return response;
}
这部分效果很好,并生成如下的JSON
:
This part works well and generates a JSON
like:
{
"creation":"12/01/2019",
"status":"paid",
"price":0.0,
"items":[
{
"name":"Math books",
"amount":"2"
},
{
"name":"Skates adult",
"amount":"1"
},
{
"name":"Tools",
"amount":"8"
}
]
}
PHP服务器端(testSendData.php
)运行不正常,我唯一设法获得的是JSON数据本身,但无法获得不同的字段:
The PHP server side (testSendData.php
) is not working well, the only I managed to get is the JSON data itself but not able to get the different fields:
$jsonData = file_get_contents("php://input");
我尝试使用json_decode
分别获取字段而没有成功,我还尝试创建php CustomerData class
来解码JSON,但仍然无法正常工作.
I tried using json_decode
to get fields individually without success, i also tried creating a php CustomerData class
to decode JSON but still not working.
获取JSON各个字段的目的是将其中一些存储在数据库中
The purpose of getting the individual fields of the JSON is to store some of them in a DB
任何帮助或参考教程,将不胜感激.
Any help or maybe a reference tutorial would be appreciated.
推荐答案
我假设您将json数据放入此变量$ jsonData
I assume you get a json data into this variable $jsonData
<?php
echo "jsondata=>".$jsonData='{
"creation":"12/01/2019",
"status":"paid",
"price":0.0,
"items":[
{
"name":"Math books",
"amount":"2"
},
{
"name":"Skates adult",
"amount":"1"
},
{
"name":"Tools",
"amount":"8"
}
]
}';
$data1 = json_decode($jsonData, TRUE);
echo "<pre>";
print_r($data1);
foreach ($data1 as $key => $value1) {
if($key=='creation'){
echo $value1."<br>";
}
if($key=='status'){
echo $value1."<br>";
}
if($key=='price'){
echo $value1."<br>";
}
if($key=='items'){
foreach ($value1 as $key1 => $value_deta) {
print_r($value_deta);
}
}
}
这篇关于从移动应用程序检索PHP上的json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!