Convert PHP array string into an array
serialize might be the right answer - but I prefer using JSON - human editing of the data will be possible that way...
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$serialized = json_encode($myArray);
$myNewArray = json_decode($serialized, true);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 )
Try using var_export to generate valid PHP syntax, write that to a file and then 'include' the file:
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$fileContents = '<?php $myArray = '.var_export($myArray, true).'; ?>';
// ... after writing $fileContents to 'myFile.php'
include 'myFile.php';
echo $myArray['key1']; // Output: value1
I think you might want to look into serialize
and unserialize
.
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$serialized = serialize($myArray);
$myNewArray = unserialize($serialized);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 )
How about eval? You should also use var_export with the return variable as true instead of var_dump.
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$fileContents = var_export($myArray, true);
eval("\$fileContentsArr = $fileContents;");
echo $fileContentsArr['key1']; //output: value1
echo $fileContentsArr['key2']; //output: value2