PHP将null写入JSON文件

时间:2017-09-26 03:54:09

标签: php json

我已经看过这个问题的类似帖子,但我似乎无法弄明白。我有一个小的PHP脚本,可以读取和写入表单输入到JSON文件,如下所示 -

  $file = 'data.json';

  $arr_data = array();

  $formdata = array(
        'name' => strip_tags( trim($_POST['formName']) ),
        'email' => $email,
        'phone' => strip_tags( trim($_POST['formPhone']) ),
        'message' => strip_tags( trim($_POST['formMessage']) )
        // also tested this just using reg strings
  );

  $jsondata = file_get_contents($file);

  //var_dump($jsondata); returns whatever string content is in the file, so seems to work

  $arr_data = json_decode($jsondata, true);

  array_push($arr_data, $formdata);

  //var_dump($arr_data); returns NULL, not sure what happens here

  $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

  file_put_contents($file, $jsondata);

有什么想法吗?使用PHP 5.5.9,检查文件是否可写。这两个文件都有UTF8编码。

2 个答案:

答案 0 :(得分:1)

如果输入为空,

NULL将返回$arr_data。试试这个以确保您的$arr_data = json_decode($jsondata, true); if ($arr_data === null) { $arr_data = []; } 是一个数组......

data4

答案 1 :(得分:1)

也许你想要这个代码

<?php
  $file = 'data.json';
  $email='your mail info';
  $arr_data = array();

  $formdata = array(
        'name' => strip_tags( trim($_POST['formName']) ),
        'email' => $email,
        'phone' => strip_tags( trim($_POST['formPhone']) ),
        'message' => strip_tags( trim($_POST['formMessage']) )
        // also tested this just using reg strings
  );

  $jsondata = file_get_contents($file);

  //var_dump($jsondata); returns whatever string content is in the file, so seems to work

  $arr_data = json_decode($jsondata, true);

  // I added for if data.json is null to empty array
  $arr_data = is_null($arr_data)?array():$arr_data;

  array_push($arr_data, $formdata);

  //var_dump($arr_data); returns NULL, not sure what happens here

  $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

  file_put_contents($file, $jsondata);
?>

他人

您应该更改代码以保持帖子数据不为空或默认值,并注意 file_get_contents 关于文件长度的方法