0

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?

2
  • Expected output ? Commented Feb 10, 2018 at 5:26
  • Please see my edit Commented Feb 10, 2018 at 5:27

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't serving me an error, but nor is it writing anything to the file.
Sorry, I left my dev file name in there for the second fopen. Fixing...
Now this script serves me up a 500 erorr
Ah. Nope. Now there was an error in my rewrite. Thanks for this. This has done it.
0
$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.