I have a PHP file to store an array:
<?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.
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.
The function you're looking for is 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.
Two alternatives:
Use a database
Serialize the array, then (over)write to file. When reading the file, you will just want to unserialize the value.
Use json_encode and json_decode as discussed in #2
There's actually several ways to achieve that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.