Home > OS >  PHP Log file not write json
PHP Log file not write json

Time:06-21

I have a problem.

my class.log.php

<?php
 
date_default_timezone_set('Europe/Istanbul');
 
class Log
{
    public function add($uID, $pID, $text)
    {
        $date = date("d.m.Y") . " " . date("H:i:s");
        $data = array("Date" => $date, "UserID" => $uID, "ProductID" => $pID, "Text" => $text);
        
        $folder = "../log/";
        $logFileName = $folder . date("d-m-Y") . ".log";
 
        if (!file_exists($folder)) {
            mkdir($folder);
        }
 
        if (!file_exists($logFileName)) {
            file_put_contents($logFileName, "\xEF\xBB\xBF");
        }
 
        $ofile = fopen($logFileName, "a");
 
        fwrite($ofile, $data);
        fclose($ofile);
    }
}
?>

I use it function like here in pages.

require_once "class.log.php";
$log = new Log();
$log->add('41','16','Product Added');

why can't I print output in json format to my .log file. I can't find where is the error in the codes

CodePudding user response:

when write to file you should convert array to string

use this code

    fwrite($ofile, json_encode($data,JSON_UNESCAPED_UNICODE));
  • Related