skygate skygate - 1 year ago 111
JSON Question

How do I record JSON data to file using PHP?

This is the code I've figured out.

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

But this is absolutely not the right way.

Answer Source

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) . ']');
        // write the first event inside an array
        fwrite($handle, json_encode(array($event)));

        // close the handle on the file

Without decoding the whole JSON file into the arrays.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download