2012-09-21 130 views
8

我想避免写入DB和使用常量/阵列郎文件等将数组写入文件的最佳方法是什么?

即:

$lang = array (
    'hello' => 'hello world!' 
); 

,并能够从后台编辑。 (然后,而不是从可怜的数据库中获取它,我只会使用$ lang ['hello'] ..)。

你认为最好和最有效的方法是什么?

+0

['var_export()'](http://uk.php.net/var_export)? – DCoder

+0

你想知道什么更有效率,存储在数据库或存储在数组中? –

+0

json_decode怎么样? –

回答

10

绝对JSON

要保存它:

file_put_contents("my_array.json", json_encode($array)); 

回来:

$array = json_decode(file_get_contents("my_array.json")); 

就这么简单!

+3

请注意,如果您想节省磁盘空间(当使用非常大的数组时),您可以始终将它作为二进制数据存储在文件中 –

5

那么如果你坚持把数据放入文件中,你可能会考虑使用php函数serialize()unserialize(),然后使用file_put_contents将数据放入文件中。

例子:

<?php 
$somearray = array('fruit' => array('pear', 'apple', 'sony')); 
file_put_contents('somearray.dat', serialize($somearray)); 
$loaded = unserialize(file_get_contents('somearray.dat')); 

print_r($loaded); 
?> 
15

最有效的方式,我发现这个样子的:

在PHP建立你的阵列不知何故并使用var_export()

file_put_contents('/some/file/data.php', '<?php return '.var_export($data_array, true).";\n"); 

然后将其导出到文件后来,无论你需要这个数据拉它像这样

$data = include '/some/file/data.php'; 
+0

我想知道,什么是更快..序列化或导出? –

+0

我宁愿在var_export上进行序列化。攻击者可能会将恶意代码放入包含变量的.php文件中并执行。 – MarcDefiant

+0

@Mogria好吧,如果攻击者能够访问语言文件,他可能会将该代码注入任何其他文件中......:) – deceze

3

您可以尝试json_encode()json_decode()

$save = json_encode($array);

的$写入内容保存到文件

要加载郎用途:

$lang = file_get_contents('langfile'); 
$lang = json_decode($lang, true); 
相关问题