[英]Save array to PHP file
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. 我使用require
打开文件,每个条目加载到一个表单中。 ( foreach
loop) I would like to save the $_POST
variables back (overwriting) to the original file in the same format . ( foreach
循环)我想以相同的格式将$_POST
变量保存回原始文件。 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. 我只需要一种方法将数组打印回原始文件。
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. 我一直无法使用print_r
,因为返回的格式不正确。 How can I do this successfully? 我怎样才能成功做到这一点? Thank you. 谢谢。
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) . ';');
You probably don't want to be re-writing your php code on the fly. 您可能不希望动态地重写您的PHP代码。
Two alternatives: 两种选择:
Use a database 使用数据库
Serialize the array, then (over)write to file. 序列化数组,然后(over)写入文件。 When reading the file, you will just want to unserialize the value. 读取文件时,您只想反序列化该值。
Use json_encode and json_decode as discussed in #2 使用#2中讨论的json_encode和json_decode
There's actually several ways to achieve that. 实际上有几种方法可以实现这一目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.