我正在利用PHP将表单中的输入字符串化为JSON。它目前正在格式化它
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf@asdf","age":"21","gender":"Male","submit":"Submit"},
但它应该看起来更像这样,对吧?
[
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf@asdf","age":"21","gender":"Male","submit":"Submit"}
]
这是我目前的PHP。我该怎么做才能使它正确串化?
<?php
if (isset($_GET['name'])){
$json_data = json_encode($_GET);
// var_dump($json_data);
$file = file_put_contents('data.json', $json_data."," , FILE_APPEND |
LOCK_EX);
?>
<script type="text/javascript">
ChangeName(<?php echo("'".$_GET['name']."'") ?>);
</script>
<?php } ?>
答案 0 :(得分:3)
执行此操作的唯一方法是首先从文件中读取数据,对其进行解码,将新数组附加到该数据并再次将其编码为json并将其放入文件中,如下所示:
<?php
if (isset($_GET['name']))
{
$data = json_decode(file_get_contents('data.json'), true);
$data[] = $_GET;
$json_data = json_encode($data);
$file = file_put_contents('data.json', $json_data);
}