将数组保存到 PHP 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18342477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save array to PHP file
提问by Mooseman
I have a PHP file to store an array:
我有一个 PHP 文件来存储一个数组:
<?php
$arr = array (
"A" => "one",
"B" => "two",
"C" => "three"
);
?>
I am using require
to open the file, and each entry loads into a form. (foreach
loop) I would like to save the $_POST
variables back (overwriting) to the original file in the same format. I have no trouble making the form and sending back the variables. I just need a way to print the array back into the original file.
我require
用来打开文件,每个条目都加载到一个表单中。(foreach
循环)我想以相同的格式将$_POST
变量保存回(覆盖)到原始文件中。我可以轻松制作表格并发回变量。我只需要一种将数组打印回原始文件的方法。
Example result:
结果示例:
<?php
$arr = array (
"A" => "new value",
"B" => "other new value",
"C" => "third new value"
);
?>
I have been unable to use print_r
, as the format returned is incorrect. How can I do this successfully? Thank you.
我一直无法使用print_r
,因为返回的格式不正确。我怎样才能成功地做到这一点?谢谢你。
回答by MosheK
The function you're looking for is var_export
您正在寻找的功能是 var_export
You would use it like this
你会像这样使用它
file_put_contents($filename, '<?php $arr = ' . var_export($arr, true) . ';');
DEMO
演示
回答by Jason Crittenden
You probably don't want to be re-writing your php code on the fly.
您可能不想即时重写您的 php 代码。
Two alternatives:
两种选择:
Use a database
Serializethe array, then (over)write to file. When reading the file, you will just want to unserializethe value.
Use json_encodeand json_decodeas discussed in #2
使用数据库
使用#2 中讨论的json_encode和json_decode
回答by vinyll
There's actually several ways to achieve that.
实际上有几种方法可以实现这一目标。
- Open your file and write into it with file_put_contents() (http://php.net/manual/fr/function.file-put-contents.php)
- write to the file your array encoded to string with JSON.encode (http://www.php.net/manual/fr/function.json-encode.php)
- read your file with file_get_contents (file_get_contents)
- convert your string to an array with JSON.decode (http://www.php.net/manual/fr/function.json-decode.php)
- 打开您的文件并使用 file_put_contents() ( http://php.net/manual/fr/function.file-put-contents.php)写入文件
- 使用 JSON.encode ( http://www.php.net/manual/fr/function.json-encode.php)将您的数组编码为字符串写入文件
- 使用 file_get_contents (file_get_contents) 读取您的文件
- 使用 JSON.decode ( http://www.php.net/manual/fr/function.json-decode.php)将您的字符串转换为数组