I try to write to JSON using php. The first time is written and you can use the file, and the second time returns null when decoding due to the wrong json file format, here is the code that writes

$name = clean($_POST['title']); $message = clean($_POST['message']); $new_post = array("title" => $name, "text" => $message); $new_post = json_encode($new_post); file_put_contents('data.json', $new_post, FILE_APPEND); echo "Success"; function clean($value = ""){ $value = htmlspecialchars(strip_tags(stripcslashes(trim($value)))); return $value; } 

And he writes in this form {"title": "value1", "text": "value2"} {"title": "value3", "text": "value4"} .... Writes in one line, does not transfer the caret below. Because of this, after the second write to this file, it cannot be used. Here is the code that reads:

 <?php $title = clean($_GET['query']); function clean($value = ""){ $value = htmlspecialchars(strip_tags(stripcslashes(trim($value)))); return $value; } $result_string = search($title); function search($title = ""){ $ret_str = ""; $text = file_get_contents('../data.json'); $obj = json_decode($text, true); echo in_array($title, $obj); foreach ($obj as $key=>$value){ if($title == $value){ $ret_str = $obj['text']; }else{ echo "WTF?!"; } } return $ret_str; } echo "<br>".$result_string; 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

JSON is not intended to record values.

A line PHP_EOL can be done using the standard constant PHP_EOL

 file_put_contents('data.json', $new_post.PHP_EOL, FILE_APPEND); 

That just does not help. Two entries should look like this:

 [ {"title":"value1", "text":"value2"}, {"title":"value3", "text":"value4"} ] 

Although in the simple case you can

  1. file to create initially with an open bracket [ and the first data record
  2. add ','.PHP_EOL.$new_json_row
  3. when reading a file, but before decoding json add to the end ] and only then decode.

But it looks like a crutch.

Without knowing the original task, it is difficult to say anything further. But most likely you would be more appropriate to take a normal DBMS.

  • You are right, you just need to demolish and install a new OS (win7). I will check it a little later and if it helps, I will install + - MaxTester