Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Variable Handling Functions : var_export

var_export

Outputs or returns a parsable string representation of a variable (PHP 4 >= 4.2.0, PHP 5)
mixed var_export ( mixed expression [, bool return] )

Example 2605. var_export() Examples

<?php
$a
= array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

The above example will output:

array (
 0 => 1,
 1 => 2,
 2 =>
 array (
   0 => 'a',
   1 => 'b',
   2 => 'c',
 ),
)
<?php

$b
= 3.1;
$v = var_export($b, true);
echo
$v;

?>

The above example will output:

3.1

Example 2606. Exporting classes since PHP 5.1.0

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

The above example will output:

A::__set_state(array(
  'var' => 5,
))

Example 2607. Using __set_state (since PHP 5.1.0)

<?php
class A
{
   public
$var1;
   public
$var2;

   public static function
__set_state($an_array)
   {
       
$obj = new A;
       
$obj->var1 = $an_array['var1'];
       
$obj->var2 = $an_array['var2'];
       return
$obj;
   }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval(
'$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                           //    'var1' => 5,
                                           //    'var2' => 'foo',
                                           // ));
var_dump($b);
?>

The above example will output:

object(A)#2 (2) {
 ["var1"]=>
 int(5)
 ["var2"]=>
 string(3) "foo"
}

Code Examples / Notes » var_export

php_manual_note

[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialize it into another variable.
Using a file created with var_export() could simply be include()'d, which will be less code and faster.
[kaja]
If you are trying to find a way to temporarily save variables into some other file, check out serialize() and unserialize() instead - this one is more useful for its readable property, very handy while debugging.
[original post]
If you're like me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as
<?php
$string = '<?php $array = ' . $data . '; ?>';
?>
where $data is the output of var_export() can create a file that can be easily include()d back into the script to recreate $array.
The raw output of var_export() could also be eval()d to recreate the array.
---John Holmes...


paul

var_export() differs from print_r() for variables that are resources, with print_r() being more useful if you are using the function for debugging purposes.
e.g.
<?php
$res = mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Resource id #14
var_export($res); //output: NULL
?>


niq

To import exported variable you can use this code:
<?
$str=file_get_contents('exported_var.str');
$var=eval('return '.$str.';')
// Now $val contains imported variable
?>


aidan

This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
http://pear.php.net/package/PHP_Compat


zorro

This function can't export EVERYTHING. Moreover, you can have an error on an simple recursive array:
$test = array();
$test["oops"] = & $test;
echo var_export($test);
=>
Fatal error:  Nesting level too deep - recursive dependency? in ??.php on line 59


glen

Like previously reported, i find var_export() frustrating when dealing with recursive structures.  Doing a :
<?php
var_export($GLOBALS);
?>
fails.  Interestingly, var_dump() has some logic to avoid recursive references.  So :
<?php
var_dump($GLOBALS);
?>
works (while being more ugly).  Unlike var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.


stangelanda

I have been looking for the best method to store data in cache files.
First, I've identified two limitations of var_export verus serialize.  It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.
However, I could deal with both of those so I created a benchmark.  I used a single array containing from 10 to 150 indexes.  I've generate the elements' values randomly using booleans, nulls, integers, floats, and some nested arrays (the nested arrays are smaller averaging 5 elements but created similarly).  The largest percentage of elements are short strings around 10-15 characters.  While there is a small number of long strings (around 500 characters).
Benchmarking returned these results for 1000 * [total time] / [iterations (4000 in this case)]
serialize 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38
Meaning serialize is around 1 and a half times faster than var_export for a single large array.  include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache like APC might make include faster, but otherwise serialize is the best choice.


dosperios

Here is a nifty function to export an object with var_export without the keys, which can be useful if you want to export an array but don't want the keys (for example if you want to be able to easily add something in the middle of the array by hand).
<?
function var_export_nokeys ($obj, $ret=false) {
$retval = preg_replace("/'?\w+'?\s+=>\s+/", '', var_export($obj, true));
if ($ret===true) {
return $retval;
} else {
print $retval;
}
}
?>
Works the same as var_export obviously. I found it useful, maybe someone else will too!


nobody

Here is a bit code, what will read an saved object and turn it into an array.
Please note: It is very lousy style. Only an an idea.
$data = file_get_contents("test.txt");
$data = preg_replace('/class .*{/im', 'array (', $data);
$data = preg_replace('/\}/im', ')', $data);
$data = preg_replace('/var /im', '', $data);
$data = preg_replace('/;/im', ',', $data);
$data = preg_replace('/=/im', '=>', $data);
$data = preg_replace('/=>>/im', '=>', $data);
$data = preg_replace('/\$(.*?) /im', '"$1"', $data);
eval('$O = ' . $data . ';');
print_r($O);


roman

Function that exports variables without adding any junk to the resulting string:
<?php
function encode($var){
   if (is_array($var)) {
       $code = 'array(';
       foreach ($var as $key => $value) {
           $code .= "'$key'=>".encode($value).',';
       }
       $code = chop($code, ','); //remove unnecessary coma
       $code .= ')';
       return $code;
   } else {
       if (is_string($var)) {
           return "'".$var."'";
       } elseif (is_bool($code)) {
           return ($code ? 'TRUE' : 'FALSE');
       } else {
           return 'NULL';
       }
   }
}
function decode($string){
   return eval('return '.$string.';');
}
?>
The resulting string can sometimes be smaller, that output of serialize(). May be useful for storing things in the database.


linus

<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speak for everyone when I ask you to test code before you add to the manual.
Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().
<?php
function var_export_min($var, $return = false) {
if (is_array($var)) {
$toImplode = array();
foreach ($var as $key => $value) {
$toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
}
$code = 'array('.implode(',', $toImplode).')';
if ($return) return $code;
else echo $code;
} else {
return var_export($var, $return);
}
}
?>


Change Language


Follow Navioo On Twitter
debug_zval_dump
doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
isset
print_r
serialize
settype
strval
unserialize
unset
var_dump
var_export
eXTReMe Tracker