Capture output of var_dump() as a string in PHP
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php function vardump($data) { ob_start(); var_dump($data); $output = ob_get_contents(); ob_end_clean(); return $output; } $person = array( "Name" => "John", // String "Age" => 32, // Integer "Hired" => true, // Boolean "Experience" => 10.5, // Float "Degree" => array('BS', 'MS'), // Array "Class" => new stdClass() // Object ); $result = vardump($person); echo $result; ?> |
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().
|
1 2 3 4 5 6 |
function vardump($data) { ob_start(); var_dump($data); return 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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $person = array( "Name" => "John", // String "Age" => 32, // Integer "Hired" => true, // Boolean "Experience" => 10.5, // Float "Degree" => array('BS', 'MS'), // Array "Class" => new stdClass() // Object ); $result = var_export($person, true); echo $result; ?> |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)