1

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が難しいため、触れないほうがよいでしょう)、コンテンツをメモリに保存せずに出力をファイルに直接ストリーミングできますか?

4

2 に答える 2

0

このファイルを引数として PHP インタープリターを使用proc_openおよび呼び出すことができます。これはデータをメモリに保存しませんが、別のプロセスを作成します。

$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);
}
?>
于 2014-06-08T04:56:48.610 に答える