Page 1 of 1

Saving arrays or interpreting Strings as PHP?

Posted: Sat Dec 05, 2009 7:11 pm
by airandfingers
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!

Re: Saving arrays or interpreting Strings as PHP?

Posted: Sat Dec 05, 2009 7:59 pm
by AbraCadaver
I've done this in the past. Write it out like this:

Code: Select all

$content = "<?php\n" .'$a = ' . var_export($a, TRUE) . ";\n?>\n"
file_put_contents('filename.php', $content);
Then when needed do this to have $a defined:

Code: Select all

include 'filename.php'; 
-Shawn

Re: Saving arrays or interpreting Strings as PHP?

Posted: Sat Dec 05, 2009 9:07 pm
by jackpf
Could also use serialize() or json.

Re: Saving arrays or interpreting Strings as PHP?

Posted: Sun Dec 06, 2009 5:39 pm
by airandfingers
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.

Re: Saving arrays or interpreting Strings as PHP?

Posted: Sun Dec 06, 2009 6:51 pm
by AbraCadaver
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.
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.

-Shawn