从PHP文件创建HTML文件


Creating HTML files from PHP files

我知道这超出了PHP的一般用途。我使用PHP为web前端生成模板。然后我将这些模板交付给开发团队。他们要求我们提供平面HTML文件。

是否有办法利用PHP保存出的html版本的文件。我有screen-02.php到screen-62.php。我必须在浏览器中单独打开这些,并将html保存为screen-02.html, screen-03.html等。如果有帮助的话,我还可以使用jQuery。

提前感谢任何帮助。

使用PHP输出缓冲?http://php.net/manual/en/function.ob-start.php

例如:

<?php
    ob_start();
    include_once("screen-01.php");
    $content = ob_get_clean();
    file_put_contents($fileName, $content);
?>

您也可以放入一个循环来同时保存所有文件,但取决于您应该检查最大执行时间

我认为编写Shell/批处理脚本并从CLI执行PHP脚本而不是将它们用作网页是最简单的事情。

如果执行以下命令:

php /some/page.php

您可以生成标准输出所需的输出,因此如果您使用流水线,您可以轻松地执行以下操作:

php /some/page.php >> /some/page.html

或者你可以写一个bash脚本(如果你在Linux上),像这样:

#!/bin/bash
for i in {1..5}
do
  php /some/screen-$i.php >> /some/screen-$i.html
done

我认为这将是最简单(也是最快)的方法,不需要其他技术。

如果您无法访问PHP CLI,您也可以做类似的事情,但是您可以使用wget来代替PHP CLI来下载页面。

最简单的方法(在我看来)是使用输出缓冲来存储并保存PHP输出。您可以在不访问命令行服务器工具的情况下使用它。

创建一个新的PHP文件:

<?php
// Start output buffering
ob_start();
// Loop through each of the individual files
for ( $j = 0; $j<= 62; $j++ ){
    ob_clean(); // Flush the output buffer
    $k = str_pad( $j, 2, '0' ); // Add zeros if a single-digit number
    require_once('screen-' . $k . '.php'); // Pull in your PHP file
    if ( ob_get_length() > 0 ){ // If it put output into the buffer, process
        $content = ob_get_contents(); // Pull buffer into $content
        file_put_contents( 'screen-' $k . '.html', $content ); // Place $content into the HTML file
    }
}
?>

在相同的服务器上以相同的路径运行它。确保该文件夹具有写权限(CHMOD),以便它可以创建新文件。您应该会发现它生成了所有HTML文件,并带有正确的PHP输出。

可以这样写:

<?php
$file = $_GET['file'];
$html = file_get_contents('http://yoururl.com/'.$file);
file_put_contents('./savedPages/'.$file.'.htm', $html);
?>

调用http://yoururl.com/savePage.php?file=yourtarget.php

当你使用像Smarty这样的模板引擎时,你可以创建输出并将其保存到一个文件中,而不需要在浏览器中显示它。

$smarty = new Smarty;
$smarty->assign("variable", $variable);
$output = $smarty->fetch("templatefile.tpl");
file_put_contents("/path/to/filename.html", $output);

Smarty文档:http://www.smarty.net/docs/en/api.fetch.tpl

另一个选择是使用PHP输出缓冲区