【发布时间】: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。