tags:

views:

41

answers:

4

Hi guys,

I have exported an array using var_export($var,true); and stored it to a file arraystore.php

When I include arraystore.php on another page and try to use the array it doesn't work? should it, or is there a way to import the var for use in the new page? Maybe serialising and sending as the constructor of the class in use on the second page? would that work?

A: 

The array is now a string in the text file. To import:

 $str=file_get_contents('arraystore.php');
 $var=eval('return '.$str.';')
Orbit
A: 

Could you show us your arraystore.php?

arraystore.php has to look similiar to this:

<?php
  $array = array(
    1 => "I'm a String",
    'stringKey' => true,
    'foo' => "bar"
  );
?>

I'm pretty sure, you forgot the php-Tags.

silvinci
A: 

You can do this by using eval:

$arrayString = file_get_contents('arraystore.php');
$array = eval('return ' . $arrayString . ';');

However, since eval is evil you might want to write the following to your file instead of the plain var_export() output:

<?php
return your_var_export_output_here;
?>

Then you will be able to use the following code to load the array:

$array = include 'arrayStore.php';

Another option would be assigning the array to a variable in your arrayStore.php and then simply using this variable after including/requiring the arrayStore.php

ThiefMaster
Why the downvote? If anything in my answer is incorrect, please leave a comment.
ThiefMaster
A: 

var_export() is not intended to be a data-interchange format. It's a debug statement. If you want to save some objects for future, serialize it instead. It handles character encoding properly as well.

$serialized_store = serialize($var);
fwrite($fp, $serialized_store);

And you can easily read it back:

$serialized_store = file_get_contents('arraystore.php');
$var = unserialize($serialized_store);

This method avoids using eval(). It is almost evil.

Still, you can use JSON for the store format.

$json_store = json_encode($var);
fwrite($fp, $json_store);
// ...
$json_store = file_get_contents('arraystore.json');
$var = json_decode($json_store);
Török Gábor
why to eval or json something that can be just included?
Col. Shrapnel
@Col. Shrapnel: it's not me to answer this but Liam Bailey. He described a problem and I provided a solution to it.
Török Gábor
He has not a single problem. var_export()/include is excellent when used properly.
Col. Shrapnel