【问题标题】:PHP code to READ JSON读取 JSON 的 PHP 代码
【发布时间】:2015-06-26 08:13:58
【问题描述】:

我正在寻找一个 php 代码来读取 JSON 对象(我将使用 Android 将其上传到 url),并且我还希望 php 函数将数据插入到我的数据库中。有人可以帮帮我吗? 这是我的 JSON 对象

{
"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();
   }    
  }
        ?>

当我输入 www.example.com/post/ 时,我收到错误 404 未找到

【问题讨论】:

  • json_decode怎么样?
  • 在谷歌上搜索“php json”就可以回答你的问题...

标签: php json database


【解决方案1】:

像这样使用 json_decode()

<?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>";
}
?>

这里是the link 函数的官方文档。

【讨论】:

  • 正确答案,但是您应该添加指向函数文档的链接。而且...单个调试输出就足够了,所以print_r() :-) More 只会让人感到困惑并且没有任何帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多