bnjunge / MPESA-API-Tutorial

This is a Daraja API MPESA tutorial repo
MIT License
52 stars 67 forks source link

Better json formating for json log files #6

Closed DanNduati closed 3 years ago

DanNduati commented 3 years ago

Here's a better way to store JSON data from callbacks for better JSON formatting to the browser

<?php
    $response = file_get_contents("php://input");
    $logfile = "doc.json";
    if(file_exists($logfile)){
        $log = fopen($logfile,"a");
        $fstat = fstat($log);
        ftruncate($log,$fstat['size']-1);//remove the bracket at the end
        fwrite($log,',');
        fwrite($log,$response);
        fwrite($log,']');
    }
    else{
        $log = fopen($logfile,"a");
        fwrite($log,'[');
        fwrite($log,$response);
        fwrite($log,']');
    }

    fclose($log);
?>