2016-09-15 70 views
1

所以我有一個應用程序打印以下日誌:不能與file_get_contens在PHP中檢索另一個字符串拼接字符串

{"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拋出一個錯誤(我不知道知道哪一個不幸)。我可以連接「正常」字符串,如「你好」。 'World'很好,所以它必須用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" } 
]} 

我想補充一點,我對我的樹莓派運行的Apache服務器上運行,但我已經安裝了PHP,有些事情做的工作,以便我認爲這與此無關。

+0

爲什麼不直接使用'RTRIM($ LOGFILE, '')'刪除最後一個逗號? – Neat

+0

我試過了,但它似乎沒有工作。 – lolzDoe

+0

哪個聲明正是拋出錯誤? –

回答

1

您可以在trim的幫助下實現此目的,以刪除換行符rtrim以消除array_map回調中的尾隨逗號。 而一些來回json_decodejson_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"}]} 
+0

這實際上工作!非常感謝!現在一直在這個問題上一整天。 :) – lolzDoe

+0

不客氣@lolzDoe –

相關問題