How to create an array from output of var_dump in

2019-02-17 17:18发布

How can I parse the output of var_dump in PHP to create an array?

标签: php var-dump
6条回答
Root(大扎)
2楼-- · 2019-02-17 17:47

Maybe you’re looking for var_export that will give you a valid PHP expression of the passed value.

查看更多
欢心
3楼-- · 2019-02-17 17:57

You can't. var_dump just outputs text but doesn't return anything.

查看更多
时光不老,我们不散
4楼-- · 2019-02-17 18:01

Perhaps you are trying to convert an object to an array? http://www.phpro.org/examples/Convert-Object-To-Array-With-PHP.html

查看更多
放我归山
5楼-- · 2019-02-17 18:01

I had a similar problem : a long runing script produced at the end a vardump of large array. I had to parse it back somehow for further analyzis. My solution was like this:

cat log.stats  | 
  sed 's/\[//g' | 
  sed 's/\]//g' | 
  sed -r 's/int\(([0-9]+)\)/\1,/g' | 
  sed 's/\}/\),/g' | 
  sed -r 's/array\([0-9]+\) \{/array(/g' > 
  log.stats.php
查看更多
我想做一个坏孩纸
6楼-- · 2019-02-17 18:05

Use var_export if you want a representation which is also valid PHP code

$a = array (1, 2, array ("a", "b", "c"));
$dump=var_export($a, true);
echo $dump;

will display

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

To turn that back into an array, you can use eval, e.g.

eval("\$foo=$dump;");
var_dump($foo);

Not sure why you would want to do this though. If you want to store a PHP data structure somewhere and then recreate it later, check out serialize() and unserialize() which are more suited to this task.

查看更多
干净又极端
7楼-- · 2019-02-17 18:06

var_export creates the PHP code, which you can run through the eval.

But I wonder, what is your idea?

查看更多
登录 后发表回答