json - Why null return for PHP array? -
so i've got datafile contain of "events" supposed in json format such: [{"id":"4f946d7a31b27", "title":"floss otter", "start":1333252800, "end":1333339199}]
where more events more json objects [{}, {}, ...]. wrote function try , datafile array of json objects unshift new event onto, , write out datafile, keep getting null return, not array.
if($_server['request_method'] == 'post'){ $title = $_post['title']; $start = $_post['start']; $end = $_post['end']; $event = array( 'id' => md5($title), 'title' => $title, 'start' => $start, 'end' => $end ); $data = get_data(); array_unshift($data, $event); if ($fp = fopen($data_file, "w")){ fwrite($fp, json_encode($data)); fclose($fp);
}
} function get_data() { $str = ""; if ($fp = fopen($data_file, "r")){ while($line = fgets($fp)) { $str = $str . $line; } $data = json_decode($str, true); return $data == null ? array() : $data; } }
if write out variable $event
instead of should array $data
, file contains json object should, i'm worried method convert file array incorrect. in advance
try
<?php function get_data($data_file) { if (!file_exists($data_file)) { return array(); } $str = trim(file_get_contents($data_file)); return 0 < strlen($str) ? json_decode($str, true) : array(); } if ($_post) { $title = $_post['title']; $start = $_post['start']; $end = $_post['end']; $event = array( 'id' => md5($title), 'title' => $title, 'start' => $start, 'end' => $end ); $data_file = __dir__ . '\file.ext'; // file contains json data $data_array = get_data($data_file); array_unshift($data_array, $event); file_put_contents($data_file, json_encode($data_array)); }
Comments
Post a Comment