将PHP输出缓冲区写入文本文件

7

我有一个更新脚本的问题。它需要运行几个小时,因此我想让它实时输出到文本文件中。

我使用以下命令开始文档:

ob_start();

然后在 while 循环内(当它遍历数据库记录时),我有这个:
$size=ob_get_length();
if ($size > 0)
{
    $content = ob_get_contents();
    logit($contents);
    ob_clean();
}

最后是logit函数

function logit($data)
{
    file_put_contents('log.txt', $data, FILE_APPEND);
}

然而日志文件仍然是空的。我做错了什么?

你检查了日志文件路径的权限吗? - Aif
2
打字错误。 :) $contents => $content - Sadat
3个回答

6
尝试
logit($content);
//           ^^ Note the missing s

0

对于任何在这里寻找此功能的人,我今天编写了一个不错的函数:

//buffer php outout between consecutive calls and optionally store it to a file:
function buffer( $toFilePath=0, $appendToFile=0 ){
    $status = ob_get_status ();
    if($status['level']===1) return ob_start(); //start the buffer
    $res = ob_get_contents();
    ob_end_clean();
    if($toFilePath) file_put_contents($toFilePath, $res, ($appendToFile ? FILE_APPEND : null));
    return $res;
}

使用示例:

buffer(); //start the buffer

echo(12345); //log some stuff
echo(678910);

$log = buffer('mylog.txt',1); //add these lines to a file (optional)

echo('Heres the latest log:'.$log);

0

$contents 不是同一个变量,而是 $content


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接