我正在处理一个记录器类,正在添加的JSON格式如下
{"log_owner" : "test123","log_message" : "Has logged in","log_timestamp" : "1397921556","log_type" : "1"}要检索它,我需要围绕所有不同的JSON对象使用方括号,如下所示:
[
{"log_owner" : "test456","log_message" : "Has logged in","log_timestamp" : "1397921856","log_type" : "2"}
{"log_owner" : "test123","log_message" : "Has logged in","log_timestamp" : "1397921556","log_type" : "1"}
]每当文件不存在时,我都设法在文件的开头插入它,但主要问题在于将结束括号移到文件的末尾,因为我要添加新的对象,为了能够覆盖最后一个方括号,我尝试移动文件指针2位置,然后将结束括号添加到每个新条目中,我试图用以下方法来完成这一任务:
if(!$content_new) {
$pos=ftell($handle);
fseek($handle,$pos-2);
}
fwrite($handle, $content);
fclose($handle);但是似乎不适用于,因为我无法将文件指针移动到任何其他行,也无法将其倒带。
我怎么能做到这一点?任何形式的指导或改进建议都会受到高度赞赏。
谢谢。
发布于 2014-04-19 21:12:39
直接解决你的问题-快速和肮脏。
<?php
function writeLog($path, $newLine)
{
$exists = file_exists($path);
$handle = fopen($path, 'c');
if (!$exists) {
// first write to log file
$line = "[" . PHP_EOL . $newLine . PHP_EOL . "]";
} else {
// file exists so it has one or more logged lines
$line = "," . PHP_EOL . $newLine . PHP_EOL . "]";
fseek($handle , -(strlen(PHP_EOL) + 1) , SEEK_END);
}
fwrite($handle, $line);
fclose($handle);
}
$path = __DIR__ . '/file.json';
// delete file if exists - for tests
if (file_exists($path)) {
unlink($path);
}
$line = '{"log_owner" : "test123","log_message" : "Has logged in","log_timestamp" : "1397921556","log_type" : "1"}';
for ($i = 0; $i < 10; $i++) {
writeLog($path, $line);
}问题
使用CSV,输出JSON
<?php
function writeLogCSV($path, $newLine)
{
$handle = fopen($path, 'a');
fputcsv($handle, $newLine);
fclose($handle);
}
function readLogCsv ($path)
{
$handle = fopen($path, 'r');
$rows = [];
while (false !== ($line = fgetcsv($handle))) {
$rows[] = array_combine(
["log_owner", "log_message", "log_timestamp", "log_type"],
$line
);
}
fclose($handle);
echo json_encode($rows);
}
$path = __DIR__ . '/file.csv';
// delete file if exists - for tests
if (file_exists($path)) {
unlink($path);
}
$line = ["test123", "Has logged in", "1397921556", "1"];
for ($i = 0; $i < 10; $i++) {
writeLogCSV($path, $line);
}
readLogCsv($path);好的部分:
问题:
将您的日志存储在数据库或使用日志记录服务,输出JSON
好零件
https://stackoverflow.com/questions/23173872
复制相似问题