I want to create one json file with arrays encoded as json line by line. So it would look something like this:
{...valid json 1...}
{...valid json 2...}
But when I use simple fwirte with "/n" flag to do this, I get an unexpected EOF in the first line of the json file. Like I couldnt create jsons one by one in a file, that has a .json extension.
Whats wrong, and how can I fix it?
EDIT. Sample code that I use:
$file = fopen("output.json", "w");
$arr = ['a', 'b'];
fwrite($file, json_encode($arr), "
");
fclose($file);
according to the manual, fwrite does accept the following three arguments:
resource $handle
string $string
int $length (optional)
So you would have to do the following:
$file = fopen("output.json", "w");
$arr = ['a', 'b'];
fwrite($file, json_encode($arr) . "
");
fclose($file);
Note that the string concatenation operator is .
(simply a dot)
Adding to @Atmoscreations answer:
Your output format is technically not valid JSON. If you want to store a list of values/objects, you should encapsulate everything in a JSON list:
[
{...valid json 1...},
{...valid json 2...},
...
{...valid json N...}
]
You can do this with your PHP objects:
$file = fopen("output.json", "w");
$arr = [
['a', 'b'],
['c', 'd'],
];
fwrite($file, json_encode($arr));
fclose($file);