【问题标题】:how to generate a static html file from the output of a php script, using php如何使用 php 从 php 脚本的输出生成静态 html 文件
【发布时间】:2011-08-06 16:40:55
【问题描述】:

我想从一个 php 文件生成一个静态 html 页面并从另一个 php 脚本中保存它。该脚本运行了一堆回显函数,当在浏览器中查看时,这些函数是一个不错的 html 页面。但是当我运行 file_get_contents 时,它会将该文件作为文件系统上的文件打开,而不是作为 url 中的文件。

我需要以 localhost/site/categories.php 的方式调用 file_get_contents 吗?我怎样才能得到这条路?这是错误的代码:

<?php
$file = file_get_contents("categories.php");
file_put_contents("categories.html", $file);
?>

【问题讨论】:

    标签: php file static get


    【解决方案1】:

    要获得完成的输出,您需要使用 PHP url 包装器功能并通过网络服务器请求它。然后就很简单了:

    copy("http://localhost/site/categories.php", "categories.html");
    

    【讨论】:

    • 效果很好! :) 进一步澄清:第二个参数必须是绝对路径,例如:/home/user/public_html/html_at_root.html。我没有设法做的是传递额外的参数,例如会话数据,所以我只是在第一个参数中使用 GET 方法传递它们。我想知道是否有更好的方法来做到这一点......
    • 我用了这个功能,我的文件被锁了,锁打不开
    【解决方案2】:

    是的 - 以 localhost 方式运行 file_get_contents - 如果您的服务器配置正确,它就不会连接到互联网,并且会以有效的方式获取您的结果,即使托管在您自己的域名上。

    <?php
    $file = file_get_contents("http://yourserver.com/site/categories.php");
    file_put_contents("categories.html", $file);
    ?>
    

    【讨论】:

    • 在我的主机环境中工作,而“copy()”方法不能,无论是用于显式域还是本地主机。
    【解决方案3】:

    我相信你可以简单地:

    $file = file_get_contents("http://localhost/site/categories.php");
    

    但是,fopen wrappers 必须启用file_get_contents() 才能读取 URL。

    【讨论】:

      【解决方案4】:

      出于安全原因,我不会使用 php 来完成。更好的方法是使用 ssh 将文件复制到所需的远程服务器:

      php script.php | ssh you@remotehost "cp - /path/to/static/file.html
      

      【讨论】:

        【解决方案5】:

        我可能在这里遗漏了要点,但也可以包含()另一个 PHP 文件,并简单地使用它来直接按需创建输出,而不是在过程中的那个阶段完全涉及网络服务器.

        【讨论】:

          【解决方案6】:

          对我来说,它被 webhook 用来创建另一个 API 驱动的文件。它用于减少 API 请求的数量。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-07-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-16
            • 1970-01-01
            • 2018-09-01
            相关资源
            最近更新 更多