2012-09-21 127 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); 
相關問題