I'm writing a PHP application that requires the ability to take an array, save it in a file, and restore the array later. Can this be easily done?
The way I've been trying to do it is converting the Array to a String, saving that String to a file, then reversing the process until I have the original Array.
I've found the var_export function, which converts an array to a String, formatted in such a way that one could re-declare an array with that String.
For example:
<?php
$a = array (1, 2, array ("a", "b", "c"));
$b = var_export($a, true);
?>
$b now contains:
array (
0 => 1,
1 => 2,
2 =>
array (
0 => 'a',
1 => 'b',
2 => 'c',
),
)
and I want to be able to recreate $a by interpreting $b as PHP code. Can this be done?
Thanks for any and all help!
Saving arrays or interpreting Strings as PHP?
Moderator: General Moderators
-
airandfingers
- Forum Newbie
- Posts: 2
- Joined: Sat Dec 05, 2009 7:05 pm
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: Saving arrays or interpreting Strings as PHP?
I've done this in the past. Write it out like this:
Then when needed do this to have $a defined:
-Shawn
Code: Select all
$content = "<?php\n" .'$a = ' . var_export($a, TRUE) . ";\n?>\n"
file_put_contents('filename.php', $content);Code: Select all
include 'filename.php'; mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Re: Saving arrays or interpreting Strings as PHP?
Could also use serialize() or json.
-
airandfingers
- Forum Newbie
- Posts: 2
- Joined: Sat Dec 05, 2009 7:05 pm
Re: Saving arrays or interpreting Strings as PHP?
Thanks for the help, both of you. I wound up using serialize() on the array, and saving it in my database in this form.
The ability to dynamically create and interpret PHP code is definitely useful though.
The ability to dynamically create and interpret PHP code is definitely useful though.
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: Saving arrays or interpreting Strings as PHP?
Yep. Had you mentioned a database and not a file that would be my recommendation. I use the array in a file for a configuration that needs to be distributed, as with a theme (HTML and graphics) that my PHP app then uses.airandfingers wrote:Thanks for the help, both of you. I wound up using serialize() on the array, and saving it in my database in this form.
The ability to dynamically create and interpret PHP code is definitely useful though.
-Shawn
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.