将php脚本输出打印到文件

将php脚本输出打印到文件

问题描述:

PHP中是否有一个本机函数或一组函数,可以让我echo并将php文件输出打印到文件中.

Is there a native function or set of functions in PHP that will allow me to echo and print php file output into file.

例如,代码将生成HTML DOM,需要将其放入.html文件中,然后显示为静态页面.

For example code will generate HTML DOM that needs to be put into .html file and then displayed as static page.

最简单的方法是创建HTML数据字符串,然后使用

The easiest method would be to create a string of your HTML data and use the file_put_contents() function.

$htmlStr = '<div>Foobar</div>';
file_put_contents($fileName, $htmlStr);

要创建此字符串,您需要捕获所有输出的数据.为此,您需要使用ob_startob_end_clean输出控制功能:

To create this string, you'll want to capture all outputted data. For that you'll need to use the ob_start and ob_end_clean output control functions:

// Turn on output buffering
ob_start();
echo "<div>";
echo "Foobar";
echo "</div>";

//  Return the contents of the output buffer
$htmlStr = ob_get_contents();
// Clean (erase) the output buffer and turn off output buffering
ob_end_clean(); 
// Write final string to file
file_put_contents($fileName, $htmlStr);


参考-


Reference -

  • ob_start()
  • ob_get_contents()
  • ob_end_clean()
  • file_put_contents()

PHP输出控制文档