1

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?

Liam Bailey
  • 5,879
  • 3
  • 34
  • 46

4 Answers4

0

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

 $str=file_get_contents('arraystore.php');
 $var=eval('return '.$str.';')
Brandon Frohbieter
  • 17,563
  • 3
  • 40
  • 62
0

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.

buschtoens
  • 8,091
  • 9
  • 42
  • 60
0

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
  • 310,957
  • 84
  • 592
  • 636
0

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);
Community
  • 1
  • 1
viam0Zah
  • 25,949
  • 8
  • 77
  • 100