繁体   English   中英

使用PHP ob_start和ob_get_clean输出流

[英]Output streaming with PHP ob_start & ob_get_clean

我有一个脚本,可在php脚本中echo内容,并导致文件很大,例如100MB

目前,我使用以下方式捕获输出并写入另一个文件

ob_start();
require_once 'dynamic_data.php'; // echo 100MB data
$data = ob_get_clean();
file_put_contents($path, $data);

是否有任何简便的方法可以重新编写上述程序(最好不要触摸dynamic_data.php ,因为很难进行dynamic_data.php ),这样它可以直接将输出流传输到文件,而无需将内容保存在内存中?

ob_start文档提供了一种解决方法。 您需要传递$output_callback$chunk_size

假设您将$chunk_size设置为1MB。 然后,每缓冲1MB的输出数据,将使用此数据调用$output_callback ,您可以将其刷新到磁盘(同时隐式刷新输出缓冲区)。

$output_callback = function($data) {
   //$buffer contains our 1MB of output

   file_put_contents($path, $data);

   //return new string buffer
   return "";
}

//call $output_callback every 1MB of output buffered.
ob_start($output_callback, 1048576);

require_once 'dynamic_data.php';

//call ob_clean at the end to get any remaining bytes 
//(implicitly calls $output_callback final time)
ob_clean();

您可以使用proc_open并以该文件作为参数调用PHP解释器。 这不会将数据存储在内存中,但是会创建另一个进程。

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("file", $path, "w"),  // stdout is a pipe that the child will write to
   2 => array("file", $path, "a") // stderr is a file to write to
);

$process = proc_open('php dynamic_data.php', $descriptorspec, $pipes);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fclose($pipes[0]);
    fclose($pipes[1]);
    $return_value = proc_close($process);
}
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM