2

I'm looking for a function to dump a multi-dimension array so that the output is valid php code.

Suppose I have the following array:

$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');

Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.

So doing something like:

dump_as_php($person);

Will output:

$person = array(
    'first'    => 'Joe',
    'last'     => 'Smith',
    'siblings' => array(
        'Jane' => 'sister',
        'Dan'  => 'brother',
        'Paul' => 'brother'
    )
);
3
  • 3
    Why do you need this? If you're intending on eval ing it later, I would say "forget that, use JSON instead". Commented Jan 10, 2010 at 22:47
  • I'm fetching some data from db and dumping it into dynamically created php files for faster future access to that data. Commented Jan 10, 2010 at 23:13
  • Isn't this what Caching is for? Have a look at php.net/manual/en/book.apc.php Commented Jan 10, 2010 at 23:38

2 Answers 2

6

var_export()

var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, This is exactly what I need. So simple. They thought of everything with the built-in functions :)
I've never even heard of this before! Kudos!
0

serialize and unserialize

This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.

The output will not be PHP code though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.