how to read output of var_export into a variable i

2019-01-18 21:39发布

问题:

the output is like below restored in a output.txt file:

array (
  'IMType' => '1',
  'Email' => 'test@gmail.com',
  'SignupName' => 'test11',
  'Password' => '11111',
  'Encrypted' => '',
  'Confirm' => '11111',
  'OldPassword' => '',
  'Name' => 'test',
  'SignupProvinceText' => 'province',
  'SignupCity' => 'cityname',
  'Street' => 'street x.y',
  'SignupIndustry' => 'IT',
  'SignupCompany' => 'jobirn',
  'SignupJt' => 'engineer',
  'CellPhoneNum' => '',
  'linked_in' => '',
)

it's in fact output of var_export(my_variable,true),but how to read it into a variable again?

回答1:

like this:

$dumpStr = var_export($var,true);
eval('$somevar = ' . $dumpStr.';');


回答2:

Perhaps you want to serialize object and then unserialize? http://php.net/serialize



回答3:

This technique is good for data cache.

< ?php

// reading data from DB or an API webservice etc.
$arrName = array();    
$arrName = call_procedure_here();

$strFileContent = "<"."?php".PHP_EOL."$"."arrName = ".var_export($arrName, true).PHP_EOL."?".">";
file_put_contents('cache_folder/arrayfilename.php', $strFileContent);
...
//later... from another process;
include 'cache_folder/arrayfilename.php';
?>


回答4:

I wrote a basic var_export parser, without eval: VarExportParser.php

Usage:

require_once('VarExportParser.php');
$parsed = VarExportParser::parse("array ('IMType' => '1', 'Email' => 'test@gmail.com')");
print(json_encode($parsed).PHP_EOL);

Outputs:

{"IMType":"1","Email":"test@gmail.com"}

You can try js version of it here: text_transform.html (the var_export to json button)



回答5:

its very simple , you must save it as php file not txt and then

just iclude it inside a variable :)

like this:

file_put_contents( '/some/file/data.php', '<?php return '.var_export( $data_array, true ).";\n" );

when you need to access it just do this :

$data = include '/some/file/data.php'


标签: php import