How do I record JSON data to file using PHP?

331

This is the code I've figured out.

<?php
$username = $_POST['username'];
$email = $_POST['email'];
$json = '{"username":"'.$username.'",'.'"email":"'.$email.'"}';
$file = fopen('token_data.json','w+');
fwrite($file, $json);
fclose($file);
?>

But this is absolutely not the right way.

565

Answer

Solution:

If your$_POST array has all of the data you need you can encode it as JSON and write to a file:

<?php

    $json = json_encode($_POST);
    $file = fopen('token_data.json','w+');
    fwrite($file, $json);
    fclose($file);
?>

If you want to append to the file you will need to read the file into an array first, add the newer parts of the array then encode it again before writing back to the file just like my friend @Rizier123 describes.

103

Answer

Solution:

Okay, I found a more efficient way to do this.

Original Answer

// read the file if present
$handle = @fopen($filename, 'r+');

// create the file if needed
if ($handle === null)
{
    $handle = fopen($filename, 'w+');
}

if ($handle)
{
    // seek to the end
    fseek($handle, 0, SEEK_END);

    // are we at the end of is the file empty
    if (ftell($handle) > 0)
    {
        // move back a byte
        fseek($handle, -1, SEEK_END);

        // add the trailing comma
        fwrite($handle, ',', 1);

        // add the new json string
        fwrite($handle, json_encode($event) . ']');
    }
    else
    {
        // write the first event inside an array
        fwrite($handle, json_encode(array($event)));
    }

        // close the handle on the file
        fclose($handle);
}

Without decoding the whole JSON file into the arrays.

People are also looking for solutions to the problem: php - Is this an acceptable way to approach a curl fail in a scrape? What would be the dry approach?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.