PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Servicii Web> <Funcţii de gestionare a variabilelor
Last updated: Fri, 25 Jul 2008

view this page in

var_export

(PHP 4 >= 4.2.0, PHP 5)

var_exportAfişează o reprezentare ca şir de caractere a unei variabile

Descriere

mixed var_export ( mixed $expression [, bool $return ] )

Această funcţie returnează o informaţie structurată despre o variabilă. Este similară funcţiei var_dump(), cu excepţia faptului că reprezentarea returnată este un cod PHP valid.

Dacă se foloseşte cel de-al doilea parametru optional cu valoarea TRUE se poate returna această reprezentare pentru a fi atribuită unei variabile.

Comparaţi var_export() cu var_dump().

<?php
$a 
= array (12, array ("a""b""c"));
var_export ($a);

/* afişează:
array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
*/

$b 3.1;
$v var_export($bTRUE);
echo 
$v;

/* afişează:
3.1
*/
?>



Servicii Web> <Funcţii de gestionare a variabilelor
Last updated: Fri, 25 Jul 2008
 
add a note add a note User Contributed Notes
var_export
sypek dot pawel at gmail dot com
08-Jul-2008 06:15
To stangelanda at arrowquick dot com:

serialize()'d array has to be unserialize()'d when the data needs to be loaded, which adds a significant (according to my own benchmark tests) overhead compared to using an include function. I actually find 'include' as the fastest possible way to retrieve cached (var_export()'ed) PHP arrays. Consider the code:

<?php

$ary
= array();

function
random_str($len = 0)
{
   static
$chars = 'ABCDEFHIJKLMNOPQRSTUVWXYZabcdefhgijklmnopqrstuvwxyz0123456789';
   if(
$len === 0)
     
$len = rand(5, 20);
  
$ret = '';
   for(
$i = 0;$i < $len;++$i)
   {
     
$ret .= $chars[rand(0, 60)];
   }
   return
$ret;
}

function
random_val($array = true)
{
   switch(
rand(0, $array ? 4 : 3))
   {
      case
0: // random integer
        
return rand(0, 2000);
      case
1: // random float
        
return floatval(rand(0, 2000) . '.' . rand(0, 99));
      case
2: // random bool
        
return rand(1,2) === 2 ? true : false;
      case
3: // random string
        
return random_str();
      case
4: // random array
        
$ary = array();
         for(
$i = 0;$i < 20;++$i)
         {
           
$ary[] = random_val(false);
         }
         return
$ary;
      default:
         return
0;
   }
}

for(
$i = 0;$i < 1500;$i++)
{
   if(
rand(1,2) === 2)
     
$ary[] = random_val(true);
   else
     
$ary[random_str()] = random_val(true);
}

/*
   the code above is used to generate a random array with at most 1500 elements, which consists of randomly generated integers, floats, booleans, strings and arrays. The array's keys might be integers or strings.
*/

$t = microtime(true);
header("Content-type: text/plain");
echo
'Saving serialized data 1000 times: ';
flush();
for(
$i = 0;$i < 1000;++$i)
{
  
file_put_contents('t_serialize.php', '<?php return \'' . serialize($ary) . '\'; ?>');
}
echo
microtime(true) - $t . "\n";
$t = microtime(true);

echo
'Saving var_exported data 1000 times: ';
flush();
for(
$i = 0;$i < 1000;++$i)
{
  
file_put_contents('t_var_export.php', '<?php return ' . var_export($ary, true) . '; ?>');
}
echo
microtime(true) - $t . "\n";
$t = microtime(true);

echo
'Loading serialized data 1000 times: ';
flush();
for(
$i = 0;$i < 1000;++$i)
{
  
$ary = unserialize(include 't_serialize.php');
}
echo
microtime(true) - $t . "\n";
$t = microtime(true);

echo
'Loading var_exported data 1000 times (include): ';
flush();
for(
$i = 0;$i < 1000;++$i)
{
  
$ary = include 't_var_export.php';
}
echo
microtime(true) - $t . "\n";

/*
   this needs to be done, because eval()'d code musn't include PHP tags (<?php and ?>)
*/
file_put_contents('t_var_export_eval.php', var_export($ary, true));

$t = microtime(true);

echo
'Loading var_exported data 1000 times (eval): ';
for(
$i = 0;$i < 1000;++$i)
{
  
$ary = eval('return ' . file_get_contents('t_var_export_eval.php') . ';');
}
echo
microtime(true) - $t . "\n";
$t = microtime(true);

?>

My results are:

Saving serialized data 1000 times: 18.801375150681
Saving var_exported data 1000 times: 18.207436084747
Loading serialized data 1000 times: 52.228559017181
Loading var_exported data 1000 times (include): 18.555495977402
Loading var_exported data 1000 times (eval): 18.961781024933

Which ends in the conclusion that var_export()'ing is slightly faster than serialize()'ing data, and include()'ing the exported data is almost 3 times faster than unserialize()'ing the serialize()'d data.
daniel at netbreeze dot com dot au
17-Jun-2008 05:26
For php version < 4.2.0 you can use the following. The output is *almost* the same just a little cleaner. The output is still valid php code.

<?php
if (!function_exists('var_export')) {
  function
var_export(&$var, $ret=true, $tab='') {
    if (
is_array($var)) {
     
$first = true;
     
$r = "array(\n";
     
$tt = "\t".$tab;
      foreach (
$var as $key=>$val) {
        if (
$first) {
         
$first = false;
        } else {
         
$r .=",\n";
        }
       
$r.=$tt.var_export($key,true,$tt).'=>'.var_export($val,true,$tt);
      }
     
$r.="\n$tab)";
    } else if (
is_numeric($var)) {
     
$r = $var;
    } else {
     
$r = "'".addcslashes($var,'\\\'')."'";
    }
    if (
$ret) {
      return
$r;
    } else {
      echo
$r;
    }
  }
}
?>
stangelanda at arrowquick dot com
29-Jun-2007 04:20
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.
Glen
23-May-2007 05:47
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.
niq
21-Mar-2007 06:44
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
?>
dosperios at dot gmail dot nospam do com
10-Oct-2006 11:19
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 at nowhere dot de
30-Aug-2006 03:48
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);
Zorro
04-Sep-2005 11:24
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
linus at flowingcreativity dot net
04-Jul-2005 09:50
<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);
    }
}

?>
roman at DIESPAM dot feather dot org dot ru
18-Mar-2005 01:46
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.
paul at worldwithoutwalls dot co dot uk
24-Nov-2004 11:22
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
?>
aidan at php dot net
10-Jun-2004 09:53
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
php_manual_note at bigredspark dot com
16-Oct-2003 12:43
[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...

Servicii Web> <Funcţii de gestionare a variabilelor
Last updated: Fri, 25 Jul 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites