如何在Drupal中缓存PHP生成的XML文件?

时间:2011-11-17 08:53:04

标签: php xml drupal caching drupal-6

我正在使用ammap来显示地图。点击后,用户将获得一个最新的Drupal 6节点列表,这些节点标记有相应的国家/地区(分类)。该列表由视图生成。为了实现这一点,我使用了基本的ammap XML代码,但我添加了一些PHP来包含视图,即:

<?php
//set the working directory
chdir('..');
define('DRUPAL_ROOT', getcwd());

//Load Drupal
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); 

header ("Content-Type:text/xml");

?>

<map map_file="maps/world3.swf" tl_long="-117.2" tl_lat="33.3" br_long="-94.5" br_lat="-33.9" zoom="299.9999%" zoom_x="-30.94%" zoom_y="-156.8%">
  <areas>
      <!-- ... -->
      <area title="ARGENTINE" mc_name="AR">
        <description><![CDATA[<?php print views_embed_view('MY_VIEW', 'VIEW_DISPLAY_ID', 'ARGUMENT'); ?>]]></description>
      </area>
      <!-- ... -->
  </areas>
</map>

现在,由于有许多标记包含视图,因此生成XML文件需要一些时间,这会导致地图的加载时间过长。出于这个原因,我想以某种方式缓存生成的XML文件 - 考虑到我需要在ammap配置文件中添加一个路径。

我怎么能这样做?

4 个答案:

答案 0 :(得分:4)

最好的方法是写一个小模块。

这是最短的:

/**
 * Implement hook_menu()
 * to define path for our xml file.
 */
function mymodule_menu() {
    $items = array();
    $items['map.xml'] = array(
        'title' => 'Map xml',
        'page callback' => 'map_get_xml',
        'access arguments' => TRUE,
        'type' => MENU_CALLBACK
    );
    return $items;
}

/**
 * Your custom function for xml file.
 */
function map_get_xml() {
    $cache = cache_get('your-cache-id');
    $xml = $cache->data;

    if (!$xml) {
        $xml = ... // perform your code to generate your XML

        cache_set('your-cache-id', $xml);
    }

    drupal_set_header("Content-Type:text/xml");
    print $xml;
    exit();
}

答案 1 :(得分:1)

您可以使用cache_set存储生成的XML,并使用cache_get检索它。

http://api.drupal.org/api/drupal/includes--cache.inc/function/cache_set/6

答案 2 :(得分:0)

我发现的另一个选择是让cron创建XML。在那种情况下,我没有使用缓存。在自定义模块中:

<?php
function MY_MODULE_cron() {

 $content = MY_MODULE_xml();
 file_put_contents($_SERVER['DOCUMENT_ROOT'] . file_directory_path() . '/MY_FILE.XML', $content);

}

function MY_MODULE_xml() {

$page_content = '<?xml version="1.0" encoding="UTF-8"?>
...';

return $page_content;

}

?>

答案 3 :(得分:0)

这张地图对每个用户来说都是不同的吗?或者它是非常通用的,因此非常静态?

如果是后者,我会生成地图(最有可能在cron上运行)并将其输出到静态文件,如sites / defaul / files / map.xml。对该文件的请求甚至不会调用PHP处理器,使其成为返回它的最快方式,对Web服务器的性能影响最小。

相关问题