从文本文件中提取多个json行并打印每一行

时间:2015-09-25 10:11:06

标签: php json

我正在尝试使我的应用程序日志文件对系统可读,我目前正在将其记录到名为AccessLog.txt

的文件中

我想要做的是允许php读取整个文件并输出设置变量,如果它们在日志中搜索时符合任何条件。

我当前的日志文件如下所示:

{"Action":"Edited file","User":null,"Timestamp":"25-09-2015 09:55","URL":"\/run.php?type=EDIT"}
{"Action":"Edited file","User":null,"Timestamp":"25-09-2015 09:55","URL":"\/run.php?type=EDIT"}
{"Action":"Edited file","User":null,"Timestamp":"25-09-2015 09:55","URL":"\/run.php?type=EDIT"}
{"Action":"Edited file","User":null,"Timestamp":"25-09-2015 09:55","URL":"\/run.php?type=EDIT"}

现在,我希望能够在此处导出所有内容以供我的搜索工作,我的问题是我尝试读取该文件,然后使用explode("\n",$File);将每行拆分为数组。

我希望以json_decode();格式获得此内容。

我试过这个:

function readFile($File){
$Path = fopen($_SERVER['DOCUMENT_ROOT']."/$File");


$Document = fread($Path);
$Data = explode("\n", $Document);

foreach ($Data as $Line){
    $Output = json_decode($Line);

    $print .= "Action: ".$Output->Action."<br/>";
    $print .= "User: ".$Output->User."<br/>";
    $print .= "When: ".$Output->Timestamp."<br/>";
    $print .= "Location: ".$Output->URL."<hr>";
}

fclose($Path);
return $print;

}

echo readFile("AccessLog.txt");

关于我在这里做错什么的提示?

1 个答案:

答案 0 :(得分:1)

首先,你不应该使用readFile,这个函数已经存在于php中。 http://php.net/manual/en/function.readfile.php

我已经为你改写了,

function readJsonFile($File){

  // open the file to with the R flag,
    $Path = fopen($File,"r");

    // if file found,
    if ($Path) {
        $print = '';

            // for each line
            while (($line = fgets($Path)) !== false) {
                $Output = json_decode($line);
                $print .= "Action: ".$Output->Action."<br/>";
                $print .= "User: ".$Output->User."<br/>";
                $print .= "When: ".$Output->Timestamp."<br/>";
                $print .= "Location: ".$Output->URL."<hr>";
            }

            // close file
        fclose($Path);
    } else {
        $print = 'Error, File not found';
    }
    return $print;
}

echo readJsonFile("AccessLog.txt");