lolzDoe lolzDoe - 1 year ago 71
JSON Question

Cannot concatenate string with another string retrieved by file_get_contens in PHP

So I got a application printing the following log:

{"date":"15/09/2016", "time":"09:29:58","temp":"17.0", "humidity":"95.0" },
{"date":"15/09/2016", "time":"09:30:01","temp":"17.0", "humidity":"95.0" },
{"date":"15/09/2016", "time":"09:30:03","temp":"17.0", "humidity":"95.0" },

And with the help of PHP I read it and print like this which works fine:

$logFile = file_get_contents( "../../../home/shares/flower_hum/humid.log" );
echo $logFile;

Now I want to convert this to a JSON object but if you noticed I am missing some brackets for it to be valid. I would need to remove the last comma sign and add some brackets, something like this:

$logFile = file_get_contents( "../../../home/shares/flower_hum/humid.log" );

$stringLength = strlen($logFile)-2; //Get the length of the log

$logFile = substr($logFile, 0,$stringLength); //Removes the last comma.

$logFile = '{"log":[' . $logFile . ']}'; //Add brackets

echo $logFile; //Print result

$json = json_decode($logFile, true); //create JSON Object

The problem is whenever I try to add a string to the $logFile variable, php throws an error (I don't know which unfortunatley). I can concatenate "normal" strings like 'Hello' . 'World' just fine so it has to do something with the get_file_contens method. But what I can find it should return a simple string.

My final output that I want should be this:

{"date":"15/09/2016", "time":"09:29:58","temp":"17.0","humidity":"95.0" },
{"date":"15/09/2016", "time":"09:30:01","temp":"17.0", "humidity":"95.0" },
{"date":"15/09/2016", "time":"09:30:03","temp":"17.0", "humidity":"95.0" }

I might add that I am running this on a Apache server running on my Raspberry Pi, but I have installed PHP and some things do work so I don't think it has anything to do with that.

Answer Source

You can achieve this with the help of trim to remove the newlines, rtrim to get rid of the trailing commas in an array_map callback. And some back and forth json_decode and json_encode

See below


$logLines = file('logfile.txt');

$entries = array_map("clean",$logLines);

$finalOutput = [
    'log'   => $entries

print json_encode($finalOutput, JSON_UNESCAPED_SLASHES);
// add the flag so the slashes in the dates won't be escaped

function clean($string){

    return json_decode(rtrim(trim($string),','),true);


This will output

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