【问题标题】:Generate php source code based on php array根据php数组生成php源码
【发布时间】:2023-04-08 22:46:02
【问题描述】:

我有一个不可修改的函数,需要几秒钟才能完成。 该函数返回一个对象数组。结果每天只改变一次。

为了加快速度,我想使用 APC 缓存结果,但托管服务提供商(共享托管环境)不提供任何内存缓存解决方案(APC、memcache、...)。

我找到的唯一解决方案是使用 serialize() 将数据存储到文件中,然后再次反序列化数据。

从数组中生成php源代码怎么样?后来我可以简单地调用

require data.php

将数据放入预定义的变量中。

谢谢!

更新:存储生成的 .html 不是选项,因为输出取决于用户。

【问题讨论】:

  • 如果您没有登录,您的提供商是否允许您的程序在运行时修改其脚本?如果我是提供者,我很想禁止这样做,因为它可能会防止病毒问题。
  • @Ira:PHP 脚本是 ascii 文件,因此它们被视为数据而不是可执行文件。服务器无法区分您写入文件的数据(比如说配置文件,或类似非常简单的数据库或其他东西)和您写入文件的数据,稍后由 PHP 解释器解析。
  • 据我所知没有限制。动态生成php文件应该没问题!

标签: php performance code-generation shared-hosting


【解决方案1】:

你的意思是这样的吗?

// File: data.php
<?php
return array(
  32,
  42
);


// Another file
$result = include 'data.php';
var_dump($result);

这已经是可能的了。要更新您的文件,您可以使用类似这样的方法

file_put_contents('data.php', '<?php return ' . var_export($array, true) . ';');

更新: 但是,serialize()/unserialize() 并将序列化的数组存储到文件中也没有错。

【讨论】:

    【解决方案2】:

    为什么不直接缓存生成的 html 页面呢?你可以很简单地做到这一点:

    // Check to see if cached file exists
    // You could run a crob job to delete this at a certain time
    // or have the cache file expire after a set amount of time
    if(file_exists('cache.html')) {
      include('cache.html');
      exit;
    }
    
    ob_start(); // start capturing output buffer
    
    // do output
    
    $output = ob_get_contents();
    $handle = fopen('cache.html', 'w');
    fwrite($handle, $output);
    fclose($handle);
    
    ob_end_flush();
    

    【讨论】:

    • 基于我在问题中提供的信息的完全有效和高性能的解决方案 - 但输出取决于用户 - 我更新了问题。谢谢!
    【解决方案3】:

    您可以将答案写入数据库,并使用函数参数作为键。

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2017-11-20
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多