This article demonstrates how to capture the output of var_dump() function as a string in PHP.

1. Using output buffering

You can capture the output of the var_dump() function to a string variable by turning on the output buffering. This can be done with the ob_start() function, which causes the output to be stored in an internal buffer. You can then copy the contents of the internal buffer to a string and discard the buffer contents. This is typically done using the ob_get_contents() and ob_end_clean() functions, respectively. Finally, you can print or save the contents of the string variable as needed. For example:

Download  Run Code

This results in below output:

array(6) {
  ["Name"]=>
  string(4) "John"
  ["Age"]=>
  int(32)
  ["Hired"]=>
  bool(true)
  ["Experience"]=>
  float(10.5)
  ["Degree"]=>
  array(2) {
    [0]=>
    string(2) "BS"
    [1]=>
    string(2) "MS"
  }
  ["Class"]=>
  object(stdClass)#1 (0) {
  }
}

 
You can further simplify the code using the ob_get_clean() function, which gets the current buffer contents and deletes the current output buffer. In other words, ob_get_clean() invokes both ob_get_contents() and ob_end_clean(). Here’s the simplified version using ob_get_clean().

2. Using var_export() function

You may want to use the var_export() function over the var_dump() function. It is similar to the var_dump() function, but the output is valid PHP code. The default behavior of the var_export() function is to output the contents. To capture the string representation of a variable, you can set the return parameter to true, as shown below:

Download  Run Code

This results in below output:

array (
  'Name' => 'John',
  'Age' => 32,
  'Hired' => true,
  'Experience' => 10.5,
  'Degree' =>
  array (
    0 => 'BS',
    1 => 'MS',
  ),
  'Class' =>
  (object) array(
  ),
)

That’s all about capturing the output of var_dump() function as a string in PHP.