读取JSON的PHP代码
我正在寻找一个php代码来读取JSON对象(我将使用Android将其上载到),并且我还希望php函数将数据插入到我的数据库中。有人能帮我吗? 这是我的JSON对象读取JSON的PHP代码,php,json,database,Php,Json,Database,我正在寻找一个php代码来读取JSON对象(我将使用Android将其上载到),并且我还希望php函数将数据插入到我的数据库中。有人能帮我吗? 这是我的JSON对象 { "id": "mID", "description": "des", "stars": "mStars", "name": "avatar", "year": "mYear", "rating": "mRating", "director": "mDirector" "url": "www.dummy.com" } 这是我的p
{
"id": "mID",
"description": "des",
"stars": "mStars",
"name": "avatar",
"year": "mYear",
"rating": "mRating",
"director": "mDirector"
"url": "www.dummy.com"
}
这是我的php代码
$app->post(
'/post/',
function () use ($app){
echo 'This is a POST route';
$json = $app->request->getBody();
$data = json_decode($json, true);
echo $data['name'];
echo $data['id'];
echo $data['description'];
echo $data['stars'];
echo $data['rating'];
echo $data['director'];
echo $data['url'];
echo $data['year'];
createMovie($data);
}
);
The following code is in a separate file. I have similar files with select statements which are working perfectly fine.
<?php
function createMovie($data) {
$conn=getDB();
if($stmt=$conn->prepare("$sql="INSERT INTO Movies (id, name,description, director, year, rating, stars, url)
VALUES ($data['id'],$data['name'],$data['description'],$data['director'],$data['year'],$data['rating'],$data['stars'],$data['url'])";
{
$stmt->execute();
$conn->close();
}
}
?>
$app->post(
“/post/”,
函数()使用($app){
回声“这是一条邮政路线”;
$json=$app->request->getBody();
$data=json_decode($json,true);
echo$data['name'];
echo$data['id'];
echo$data['description'];
echo$数据['stars'];
echo$数据[‘评级’];
echo$data['director'];
echo$data['url'];
echo$数据[‘年’];
createMovie($data);
}
);
以下代码位于单独的文件中。我有类似的文件和select语句,它们工作得非常好。
使用json_decode()如下所示:
这是函数的官方文档。json_decode如何?在google上搜索“php json”就可以回答您的问题……正确答案可能重复,但是您应该添加函数文档的链接。和一个调试输出就足够了,因此,print_r()
:-)More只会让人困惑,没有任何帮助。
<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>