[英]Output streaming with PHP ob_start & ob_get_clean
I have a script that echo
out content in a php script and resulting in a very large file, eg 100MB 我有一个脚本,可在php脚本中
echo
内容,并导致文件很大,例如100MB
Currently I use the following way to capture the output and write to another file 目前,我使用以下方式捕获输出并写入另一个文件
ob_start();
require_once 'dynamic_data.php'; // echo 100MB data
$data = ob_get_clean();
file_put_contents($path, $data);
Are there any easy way to re-write the above program (better not touching dynamic_data.php
as it is hard to re-factor) so it can stream the output to the file directly without saving the content in the memory? 是否有任何简便的方法可以重新编写上述程序(最好不要触摸
dynamic_data.php
,因为很难进行dynamic_data.php
),这样它可以直接将输出流传输到文件,而无需将内容保存在内存中?
The ob_start
documentation provides a workaround for this. ob_start
文档提供了一种解决方法。 You need to pass in a $output_callback
and a $chunk_size
. 您需要传递
$output_callback
和$chunk_size
。
Say you set $chunk_size
to 1MB. 假设您将
$chunk_size
设置为1MB。 Then every 1MB of buffered output data, your $output_callback
will be called with this data and you can flush it to disk (meanwhile the output buffer is implicitly flushed). 然后,每缓冲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();
You can use proc_open
and invoke the PHP interpreter with this file as argument. 您可以使用
proc_open
并以该文件作为参数调用PHP解释器。 This will not store the data in memory but it'll create another process. 这不会将数据存储在内存中,但是会创建另一个进程。
$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.