php - 创建一个动态php文件并定义一个数组

标签 php

我需要定期更新一些静态站点数据,因此我正在考虑将其保持在服务器上易于使用的格式。

我正在考虑创建一个可以包含在代码中的 php 文件,因此准备数据与浏览器请求分开。

我从数据库获取数据,所以我现在有一个键值格式的数组。

现在我想创建一个 php 文件,它只定义该数组。

键和值将是基于字符串的值,数据为瑞典语。

有没有办法直接将数组转储到文件中,然后只包含该文件而不进行任何预处理。我想要以下输出中的文件:

$array = array ();
$array ["key"] = "value";
$array ["key"] = "value";
$array ["key"] = "value";
$array ["key"] = "value";

最佳答案

我还建议查看 var_export因为您无需序列化和编码即可使用它。

例如(未经测试):

<?php
$array = array('key' => 'v');
$exported = var_export($array, TRUE);
file_put_contents('/path/to/file', '<?php $var = ' . $exported . '; ?>');
?>

然后您可以通过以下方式读回它:

<?php
include '/path/to/file';
// and now you have access to $var
// of course you may want to change the name of the $var variable as it
// will be brought into global scope (and might conflict)
?>

关于php - 创建一个动态php文件并定义一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7995685/

相关文章:

javascript - Zend 1.12 : Append javascript to bottom of view

php AES 加密的 Java 等效项

php - 解析 xml 响应奇怪

php - 如何让 str_replace 识别使用 glob 检索的文件名中的变音符号(在 Mac 上)?

php - 如何在 PHP 中使用 Microsoft SQL 驱动程序选择 SCOPE_IDENTITY()?

php - 将服务器 PHP 从 5.6 更改为 7.2 导致时区更改为 UTC

php - 每行打印 ">"

php - 拉维 SQL Server : SQLSTATE[HY000]: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Protocol error in TDS stream

php - 使用全日历查询数据库

php - 客户端-服务器架构决策