欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php var_export

shiping1 的头像

var_export

(PHP 4 >= 4.2.0, PHP 5)

var_export  输出或返回一个变量的字符串表示

reject note 描述

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

此函数返回关于传递给该函数的变量的结构信息,它和 var_dump() 类似,不同的是其返回的表示是合法的 PHP 代码。

您可以通过将函数的第二个参数设置为 TRUE,从而返回变量的表示。

比较 var_export()  var_dump().

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

/* 输出:
array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
*/


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

/* 输出:
3.1
*/

?>
</pre>


Web 服务><var_dump
[edit] Last updated: Fri, 13 Sep 2013
 
reject note add a note add a noteUser Contributed Notes var_export - [25 notes]
php_manual_note at bigredspark dot com
9 years ago
[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...
Anonymous
1 year ago
There is an even simpler way to have clean output from var_export and print_r in html pages:

<?php 
function pretty_var($myArray)
{ 
    echo 
"<pre>";
    
var_export($myArray);
    echo 
"</pre>";
} 

?>
Glen
6 years ago
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.
linus at flowingcreativity dot net
8 years ago
<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);
    }
}


?>
john dot risken at gmail dot com
3 years ago
I didn't see this simple little item anywhere in the user notes. Maybe I'm blind! 

Anyway, var_export and print_r both use spaces and carriage returns for formatting.  Sent to an html page, most of the formatting is lost. This simple function prints a nicely formatted array to an html screen: 

<?php 
function pretty_var($myArray){ 
    print 
str_replace(array("\n"," "),array("<br>","&nbsp;"), var_export($myArray,true))."<br>"; 
} 

?>
rarioj at gmail dot com
3 years ago
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.

This is an example (object Test that contains an instance of Exception).

<?php

class Test
{
  public 
$one;
  public 
$two;
  public function 
__construct($one, $two)
  {
    
$this->one = $one;
    
$this->two = $two;
  }
  public static function 
__set_state(array $array)
  {
    return new 
self($array['one'], $array['two']);
  }
}


$test = new Test('one', new Exception('test'));

$string = var_export($test, true);

/* $string =
Test::__set_state(array(
   'one' => 'one',
   'two' => 
  Exception::__set_state(array(
     'message' => 'test',
     'string' => '',
     'code' => 0,
     'file' => 'E:\\xampp\\htdocs\\test.Q.php',
     'line' => 35,
     'trace' => 
    array (
    ),
     'previous' => NULL,
  )),
))
*/


eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state

?>

So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialize() and unserialize() functions.

<?php

$string 
= 'unserialize('.var_export(serialize($test), true).')';

eval(
'$test2 = '.$string.';');

var_dump($test == $test2); // bool(true)

?>
ravenswd at gmail dot com
4 years ago
The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print 
('$bigarray', $bigarray);
?>

and it will return:

$bigarray['firstelement'] = 'something'
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! 
is_array($varval)):
    print 
$varname . ' = ' . $varval . "<br>\n";
  else:
    foreach (
$varval as $key => $val):
      
recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}

?>
Zorro
8 years ago
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
sergei dot solomonov at gmail dot com
11 months ago
<?php 
$closure 
= function(){}; 

var_export($closure); 

// output: Closure::__set_state(array()) 
?>
ravenswd at gmail dot com
4 years ago
(This replaces my note of 3-July-2009. The original version produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second version of the function.)

The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print 
('$bigarray', $bigarray);
?>

and it will return:

$bigarray = array()
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! 
is_array($varval)):
    print 
$varname . ' = ' . $varval . "<br>\n";
  else:
    print 
$varname . " = array()<br>\n";
    foreach (
$varval as $key => $val):
      
recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}

?>

For those who want a version that produces valid PHP code, use this version:

<?php
function recursive_print ($varname, $varval) {
  if (! 
is_array($varval)):
    print 
$varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print 
$varname . " = array();<br>\n";
    foreach (
$varval as $key => $val):
      
recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}

?>

If your output is to a text file and not an HTML page, remove the <br>s.
laszlo dot heredy at gmail dot com
2 years ago
Try this function instead of var_export($GLOBALS) or var_dump($GLOBALS) when all you want to know is the values of the variables you set on the current page. 

<?php 
function globalvars(){ 
    
$result=array(); 
    
$skip=array('GLOBALS','_ENV','HTTP_ENV_VARS', 
                        
'_POST','HTTP_POST_VARS','_GET', 
                        
'HTTP_GET_VARS', 
                        
'_COOKIE', 
                        
'HTTP_COOKIE_VARS','_SERVER', 
                        
'HTTP_SERVER_VARS', 
                        
'_FILES','HTTP_POST_FILES', 
                        
'_REQUEST','HTTP_SESSION_VARS', 
                        
'_SESSION'); 
    foreach(
$GLOBALS as $k=>$v) 
        if(!
in_array($k,$skip)) 
            
$result[$k]=$v; 
    return 
$result; 
}
//functionglobalvars 

var_export(globalvars()); 
?>
jodybrabec at gmail dot com
1 year ago
WORKAROUND for error "Nesting level too deep - recursive dependency":
ob_start();
var_dump($GLOBALS);
$dataDump = ob_get_clean();
echo $dataDump;
paul at worldwithoutwalls dot co dot uk
8 years ago
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
?>
stangelanda at arrowquick dot com
6 years ago
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.
kexianbin at diyism dot com
1 year ago
to use my_var_export(), it is as beautiful as var_export() and as could deal with recursive reference as print_r():

<?php
function my_var_export($var, $is_str=false)
         {
$rtn=preg_replace(array('/Array\s+\(/', '/\[(\d+)\] => (.*)\n/', '/\[([^\d].*)\] => (.*)\n/'), array('array (', '\1 => \'\2\''."\n", '\'\1\' => \'\2\''."\n"), substr(print_r($var, true),0, -1));
          
$rtn=strtr($rtn, array("=> 'array ('"=>'=> array ('));
          
$rtn=strtr($rtn, array(")\n\n"=>")\n"));
          
$rtn=strtr($rtn, array("'\n"=>"',\n", ")\n"=>"),\n"));
          
$rtn=preg_replace(array('/\n +/e'), array('strtr(\'\0\', array(\'    \'=>\'  \'))'), $rtn);
          
$rtn=strtr($rtn, array(" Object',"=>" Object'<-"));
          if (
$is_str)
             {return 
$rtn;
             }
          else
              {echo 
$rtn;
              }
         }


?>
cmusicfan (at) gmail (daught) com
4 years ago
Caution! var_export will add a backslash to single quotes (').

You may want to use stripslashes() to remove the mysteriously added backslashes.
4n4jmza02 at sneakemail dot com
3 years ago
I learned the hard way that if var_export encounters a resource handle it exports it as "NULL", even if it is a valid handle. The documentation states that a handle cannot be exported, but it does not describe what happens if you try to do so anyway.

I had been using var_export in some debugging code while tracing a problem with a resource handle not being generated and ended up thinking that null handles were still being generated long after the problem had been fixed.
niq
6 years ago
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
?>
roman at DIESPAM dot feather dot org dot ru
8 years ago
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.
nobody at nowhere dot de
7 years ago
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);
NitPicker
2 months ago
When it comes to HTML output (as discussed below), it's all fun and games until someone pokes their eye out with a "<".

Surround it with "<pre>", but do remember to wrap it in htmlspecialchars() as well.
aidan at php dot net
9 years ago
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
programistka dot php at gmail dot com
1 year ago
Example below shows how to use (e.g.) database stored settings as structurized array/object

My input array (pairs settings name and its value) is:

Array
(
    [commision.makler.level.1] => 1.0
    [commision.makler.level.2] => 1.2
    [commision.makler.level.3] => 1.4
    [commision.makler.level.4] => 1.5
    [commision.makler.level.5] => 2
    [commision.makler.level.6] => 3
    [commision.customer.level.0] => 10
    [commision.customer.level.1] => 4
    [commision.customer.level.2] => 3
    [commision.customer.level.3] => 2
    [commision.customer.level.4] => 1
)

When i use my paramsToVar() function on this array 

$oSettings = paramsToVar($myArray,true);

... i'll get struturized object: 

stdClass Object
(
    [commision] => stdClass Object
        (
            [makler] => stdClass Object
                (
                    [level] => stdClass Object
                        (
                            [1] => 1.0
                            [2] => 1.2
                            [3] => 1.4
                            [4] => 1.5
                            [5] => 2
                            [6] => 3
                        )

                )

            [customer] => stdClass Object
                (
                    [level] => stdClass Object
                        (
                            [0] => 10
                            [1] => 4
                            [2] => 3
                            [3] => 2
                            [4] => 1
                        )

                )

        )
)

Now I can easily access my settings or group of settings e.g. 
    $oSettings->makler->level

function settingsToVar($inputArray, $returnAsObject =false, $levelSeparator ='.')
{
    $temp = array();
    foreach ($inputArray as $key => $setting) {
        $value = var_export($setting,true);
        eval('$temp["'.str_replace($levelSeparator,'"]["',$key).'"] = '.$value.';');
    }
    
    if (!$returnAsObject) {
        return $temp;
    }
    
     $replacements = array('array ('=>' (object) array(');
    $varToStr = str_replace(array_keys($replacements), array_values($replacements),  var_export($temp,true));
     eval('$return = '.$varToStr.';');
     return $return;
}
dosperios at dot gmail dot nospam do com
6 years ago
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!
Hayley Watson
1 year ago
Although var_export() describes an object in terms of code that calls its class's __set_state() method, that code is only useful as such (for code generation purposes, say) if the class actually HAS a __set_state() method.

Classes don't have __set_state(), in other words; you have to provide it with one yourself (just like __toString()).

来自 http://php.net/manual/zh/function.var-export.php

普通分类: