无法将字符串与PHP中的file_get_contens检索的另一个字符串连接起来

时间:2016-09-15 07:57:46

标签: php json string concatenation filereader

所以我得到了一个打印以下日志的应用程序:

{"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" },

在PHP的帮助下,我阅读并打印出这样的工作正常:

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

现在我想将它转换为JSON对象,但是如果你注意到我错过了一些括号使它有效。我需要删除最后一个逗号符号并添加一些括号,如下所示:

<?php
 $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
?>

问题是每当我尝试将字符串添加到$ logFile变量时,php会抛出一个错误(我不知道哪个不幸)。我可以连接像'Hello'这样的“普通”字符串。 '世界'很好,所以它必须使用get_file_contens方法做一些事情。但我发现它应该返回一个简单的字符串。

我想要的最终输出应该是:

{"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" }
]}

我可能会补充一点,我在运行在我的Raspberry Pi上的Apache服务器上运行它,但是我已经安装了PHP并且有些东西可以工作,所以我认为它与此无关。

1 个答案:

答案 0 :(得分:1)

您可以在rtrim的帮助下实现此目的,以删除新行array_map以删除json_decode回调中的尾随逗号。 还有一些来回json_encode<?php $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); }

见下文

{"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"}]}

这将输出

break;