Capture the Output of var_dump in a String
April 17, 2011

Introduction

You are programming in PHP and you have an array variable that you'd like to explore at different execution paths. Of course, the best way is to use a PHP debugger like xdebug or Zend Debugger, but, what happens when you're too lazy to install a debugger? What happens when you don't want or can't install a debugger and you just need to check the content of that array by dumping it in your log file? Well, you might think you're stuck, but, read on...

What is var_dump?

The var_dump manual page states that var_dump displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

The problem is that var_dump outputs its result directly to the browser, how can you capture its output in a string variable? read on...

Using output control functions for the solution

Output control functions can be used to capture and redirect the standard output. For more details, read the PHP manual on output control functions, of course.

Here's the solution:


<?php

function varDumpToString($var) {
    ob_start();
    var_dump($var);
    $result = ob_get_clean();
    return $result;
}

//
//Example usage:
//    $data = array('first', 'second', 'third');
//    $result = varDumpToString($data);
//

All you have to do now is call the varDumpToString function. Happy coding!


Development PHP

Share this post


Written by
Mario Awad

Founder of SOFTKUBE, lead developer, and getting things done addict. Passionate about open source, user interface design, business development, and the tech world.

More about Mario Awad


About
SOFTKUBE

A small team of experts developing simple, usable, and high-quality web solutions. We blog about business, entrepreneurship, web development, and technology.

More about us


Recent Posts

Shared Office Space for Rent in Dekwaneh, Beirut, Lebanon as a Professional Work Environment

Transform your Custom PHP Script into a Globally Available CLI Command

Using Google for Live Unit Conversions

Declaring a Constant Array in PHP

View all posts


All Posts Categories

Business CLI Development Downloads Drupal Email Google Apps Multilingualism Open Source PHP Security SEO Technology Windows Zend Framework