php - 想要将目录中的所有php文件渲染或生成为静态html

标签 php html

我正在为一家本地企业开发一个小型网络项目。我为此使用了 PHP 包含文件和普通 PHP 模板,因为我发现 CMS 对于该任务来说太大了。

我正在尝试使用 ob_start()、ob_get_contents() 将项目目录中的所有 .php 文件生成为静态 .html:

ob_start();
$page = ob_get_contents();
ob_end_clean();
$out = "pages/page-1";
$file = $out.'/'. "filename.html";
@chmod($file,0755);
$fw = fopen($file, "w");
fputs($fw,$page, strlen($page));
fclose($fw);

这会生成当前页面(编写代码的位置),但我坚持对所有 .php 文件手动执行此操作,而不是将其添加到每个页面。

更新: 这是基本结构:

- index.php
- /about
 --- about-us.php
 --- our-story.php
- /products
 --- interior/
  --- some-product.php
 --- exterior/
  --- some-product.php
  --- some-other-product.php
- /contact
 --- contact.php
 --- quote.php
- /includes (config,base.php,header.tpl,footer.tpl,...templates)
- /css/js/images/assets...

我会将脚本放在同一文件夹中,它不应该自行渲染,html 输出将转到/out 文件夹。

最佳答案

这是一个简单的脚本实现:

  1. 在目录中查找 .php 文件
  2. 运行每个 .php 文件
  3. 将输出转储到同名的 .html 文件

这不是递归的,但我没有足够的有关您网站结构的信息来做出太多假设。

如果您更新您的问题,我可以更新我的答案 - 您可以使用 RecursiveDirectoryIterator 和恰当命名的 RecursiveRecursiveIterator 来递归文件结构。

无论如何,这应该提供一个起点:

<?php

$iterator = new DirectoryIterator(__DIR__);

function isValidFile(SplFileInfo $fileInfo)
{
    return $fileInfo->isFile()
        && 'php' === $fileInfo->getExtension()
        && basename(__FILE__) !== $fileInfo->getBasename();
}

function parseFile(SplFileInfo $fileInfo)
{
    ob_start();
    require_once $fileInfo->getBasename();
    $data = ob_get_contents();
    ob_end_clean();

    return $data;
}

foreach ($iterator as $fileInfo) {
    if (isValidFile($fileInfo)) {
        $data = parseFile($fileInfo);
        $file = $fileInfo->getBasename('.php') . '.html';
        file_put_contents($file, $data);
    }
}

给定这样的文件结构:

enter image description here

您最终应该得到以下结果(假设 dir 是可写的):

enter image description here

希望这有帮助:)

关于php - 想要将目录中的所有php文件渲染或生成为静态html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028857/

相关文章:

html - 无效的属性值 CSS GRID

html - 使用 Css calc() 对齐伪元素以在所有屏幕上工作

PHP strtotime 返回 UTC 时间戳?

php shell命令错误GLIBCXX_3.4.9未找到

php - 使用差异/补丁合并 PHP 更改

PHP连接Hotmail发送邮件?

javascript - 需要有关 insideHTML 和数组输入变量的帮助

php - 如何从这些给定表中的以下内容中检索帖子

PHP PDO 未从 MSSQL 存储过程调用中找到 OUTPUT 参数

html - 如何设置html标题标签的大小