DanMad
DanMad

Reputation: 1755

Writing to existing JSON array with php

Disclaimer: I am very unfamiliar with PHP. The answers I have seen floating around Stack don't seem applicable to my situation. This could be due to my unfamiliarity.

I need to write to an existing array in a JSON file:

[
    [
        // data should be written to this array
    ],
    []
] 

My PHP looks like so:

<?php
    $ip = $_POST["ip"];
    $likes = "../data/likes.json";
    $fp = fopen($likes, "a");
    fwrite($fp, json_encode($ip) . ", ");
    fclose($fp);
?>

When the PHP runs it writes to the end of the file like so (as you'd expect):

[
    [

    ],
    []

]"data",

How do I resolve my PHP to do so?

Upvotes: 0

Views: 66

Answers (2)

Alex Kapustin
Alex Kapustin

Reputation: 2459

$ip = $_POST["ip"];
$likes = json_decode(file_get_contents("../data/likes.json"), true);
$likes[] = $ip;
file_put_contents("../data/likes.json", json_encode($likes));

You can not fimply add record to file and get valid json jbject. So idea of that code: we read all from file, append array with new data, and rewrite file with new data

Upvotes: 0

sorak
sorak

Reputation: 2633

Open the file:

$filename = '../data/likes.json'
$fp = fopen($filename, 'r');

Then read the existing data structure into a variable:

$data = json_decode(fread($fp, filesize($filename)));

Add the data to the correct array entry:

$data[0][] = $ip;

Close and reopen the file with write privileges, so that we overwrite its contents:

fclose($fp);
$fp = fopen($filename, 'w');

And write the new JSON:

fwrite($fp, json_encode($data));

Upvotes: 1

Related Questions