我需要定期更新一些静态站点数据,因此我正在考虑将其保持在服务器上易于使用的格式。
我正在考虑创建一个可以包含在代码中的 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/