将 PHP 输出保存到静态文件的最佳方法?

Best way to save PHP output to a static file?

我有一个 PHP 页面输出 XML。但出于效率原因,最好提供 XML 页面。正确的?

XML 是播客 RSS 数据。 http://kansaspublicradio.org/widgets/podcasts/retro-cocktail-hour.php 另一个节目还有一个类似的。 PHP 代码从我们的 CMS (drupal) 收集数据并将其放入 iTunes 特定的 XML 标签中。我发现这是比任何可用的 drupal 模块更好的解决方案。

但是用 PHP 文件提供 XML 有点不合常规。并且 PHP 代码将在任何时候执行,或者任何 事物 即 itunes 或 feedburner,请求 RSS 数据。 PHP 代码只是查询数据库,然后循环遍历结果以写入 XML 标记,但仍然存在固有内存并且每次都会影响 sql 性能。

所以我需要提供静态 XML 文件。如何将 PHP 的输出保存到文件中??

我想我会创建另一个 PHP 脚本,例如 makepodcast.php,它运行原始 PHP 页面但将其输出打印到 XML 页面。然后我可以做一个每周一次的 cron 工作(节目每周录制一次)。

但我迷失的是我究竟如何保存 PHP 的输出并将其写入另一个文件??

But it's a little unconventional to serve XML with a PHP file.

这其实很常规。

And that PHP code will be executed anytime anyone, or anything i.e. itunes or feedburner, makes a request for the RSS data.

考虑缓存输出 - PHP 的 APC 对此非常方便,或者您可以使用 file_get_contents / file_put_contents 使您自己的变得非常简单基于文件的缓存。

您必须组织 XML 的构建:每个周期、每个信号、每个事件? 完成后,您可以编写如下内容:

<?php
    header("Content-type: text/xml");

    define ('XML_FILE_PATH', 'CUSTOMIZE/YOUR/XML/FILE/PATH');

    if ($_MUST_BUILD_XML) {
        // put here your old PHP code that it will build your XML file 
        // i guess that it is something like $xml = '<xml>
        //                                              <videogame>
        //                                                  <ps4>The Best One :) </ps4>
        //                                              </videogame>'
        buildXmlFile('built_file.xml', $xml);
        print $xml;
    }
    else {
        print readXmlFile('built_file.xml'); 
    }

    /**
      * @return string : built XML data
      * @param string  : XML file path and name
      * @throws Exception
      */
    function buildXmlFile($data_s, $file_name_s) {
        $fp = fopen ("XML_FILE_PATH/" . $file_name_s , "w");
        if(!$fp) { 
            /*TODO Error*/ throw new Exception('...');
        }

        fputs($f, $data_s);
        fclose ($f);
    }

    /**
      * @param string  : XML file path and name
      * @return string : built XML data
      * @throws Exception
      */
    function readXmlFile($file_name_s) {
        $fp = fopen ("XML_FILE_PATH/" . $file_name_s , "r");
        if(!$fp) { 
            /*TODO Error*/ throw new Exception('...');
        }

        $contents = fread($fp, filesize("XML_FILE_PATH/" . $file_name_s);
        fclose ($f);
        return ($contents);
    }

希望对您有所帮助:)