【问题标题】:.json File Keeps Going Null.json 文件一直为空
【发布时间】:2019-07-26 03:42:36
【问题描述】:

我正在尝试使用 html 和 php 创建一个小型用户注册系统。 我正在尝试将所有输入的用户名保存到 json 文件中。 这是我的代码

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
<form action="reg.php" method="post">
  Username: <input type="text" name="username">
  Password: <input type="text" name="password">
  <input type="submit">

</form>


<?php

$myFile = "data.json";
   $arr_data = array(); // create empty array

  try
  {
       //Get form data
       $formdata = array(
          'firstName'=> $_POST['username'],
       );

       //Get data from existing json file
       $jsondata = file_get_contents($myFile);

       // converts json data into array
       $arr_data = json_decode($jsondata, true);

       // Push user data to array
       array_push($arr_data,$formdata);

       //Convert updated array to JSON
       $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

       //write json data into data.json file
       if(file_put_contents($myFile, $jsondata)) {
            echo 'Data successfully saved';
        }
       else
            echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }





 ?>




  </body>
</html>

但它总是说

警告:array_push() 期望参数 1 为数组,在第 35 行的 C:\Users\XooT\PHP\User_database\reg.php 中给出 null

我能做什么,有什么问题??谁能帮帮我

【问题讨论】:

  • 可能是因为“data.json”在第一次调用时为空,因此file_get_contents 是一个空字符串。
  • JSON 可能格式不正确且未形成关联数组。或者 file_get_contents() 返回 NULL。尝试var_dump()print_r 检查$jsondata$arr_data

标签: php arrays json arraylist


【解决方案1】:

该错误意味着您的array_push($arr_data, $formdata); 中的$arr_data 是一个空字符串。

也许您现有 JSON 文件的路径有误?

通过转到print_r($jsondata) 来检查$jsondata 变量中的内容

【讨论】:

  • 感谢您的帮助.. 问题是 .json 文件一开始是空的.. 所以只需要稍微填一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 2013-11-14
相关资源
最近更新 更多