Question
I want to capture the output of var_dump() into a string in PHP instead of sending it directly to the browser.
The PHP documentation says that because var_dump() outputs its result directly, output-control functions can be used to capture that output and store it in a string.
What does that look like in practice?
print_r() is not a suitable alternative here, because it does not provide the level of detail I need.
Short Answer
By the end of this page, you will understand how to capture the output of var_dump() into a PHP string using output buffering. You will also see when this is useful, how it works internally, common mistakes to avoid, and practical examples for debugging, logging, and inspecting complex values.
Concept
var_dump() is a PHP debugging function that prints detailed information directly to output. That means it does not return the dump as a string that you can store in a variable.
This is different from functions that return values normally.
For example:
$name = strtoupper("hello");
Here, strtoupper() returns a string, so you can assign it.
But with var_dump():
$result = var_dump([1, 2, 3]);
var_dump() writes its output immediately and returns null, so $result will not contain the dump text.
To capture that printed output, PHP provides output buffering. Output buffering temporarily stores anything that would normally be sent to the browser. You can then retrieve that buffered output as a string.
This matters because in real programming you may want to:
- log debug output to a file
- send diagnostic information in an email
- include debug text in an API response during development
- inspect complex arrays or objects without printing directly
Mental Model
Think of var_dump() like a person speaking into a room instead of handing you a note.
- Normally, the words go straight to the audience (the browser).
- Output buffering is like placing a recorder in the room.
- After
var_dump()speaks, you stop the recorder and save the recording as a string.
So instead of:
- “say it directly to the browser”
you get:
- “capture what was said and store it for later”
That is exactly what output buffering does in PHP.
Syntax and Examples
The basic pattern is:
ob_start();
var_dump($value);
$output = ob_get_clean();
What each function does
ob_start()starts output buffering.var_dump($value)prints to the buffer instead of directly to the browser.ob_get_clean()gets the buffered content as a string and ends buffering.
Example 1: Capture a simple array
<?php
$data = ["name" => "Alice", "age" => 30, "active" => true];
ob_start();
var_dump($data);
$dump = ob_get_clean();
echo "Captured dump:\n";
echo $dump;
Possible output:
Captured dump:
array(3) {
["name"]=>
string(5) "Alice"
["age"]=>
int(30)
["active"]=>
bool(true)
}
Step by Step Execution
Consider this code:
<?php
$item = ["x" => 10, "y" => 20];
ob_start();
var_dump($item);
$dump = ob_get_clean();
echo "Stored length: " . strlen($dump);
Step-by-step
$itemis created as an array with two keys.ob_start()tells PHP to begin buffering output.var_dump($item)runs.- Normally, this would print directly to the browser.
- Because buffering is active, the text is stored in memory instead.
ob_get_clean()does two things:- gets the buffered output as a string
- closes and clears the buffer
- The string is assigned to
$dump. strlen($dump)measures how many characters are in the captured dump.echoprints only the length message.
Real World Use Cases
Here are some practical situations where capturing var_dump() output is useful.
Debug logging
When debugging complex arrays or objects, you may want to save detailed output to a file:
ob_start();
var_dump($responseData);
$dump = ob_get_clean();
file_put_contents('api-debug.log', $dump, FILE_APPEND);
Error reports
If an error occurs, you can capture variable state and include it in diagnostics:
ob_start();
var_dump($payload);
$payloadDump = ob_get_clean();
error_log("Invalid payload:\n" . $payloadDump);
Development-only API debugging
During local development, you may want to include debug info in a JSON response or separate text output.
Inspecting nested objects
var_dump() is often more detailed than simpler output tools because it shows:
- data types
- string lengths
Real Codebase Usage
In real projects, developers usually use this technique as a temporary debugging tool or wrap it in helper utilities.
Common pattern: helper function
function dump_to_string($value): string
{
ob_start();
var_dump($value);
return ob_get_clean();
}
This avoids repeating buffering code everywhere.
Common pattern: conditional debugging
if ($debugMode) {
$dump = dump_to_string($config);
error_log($dump);
}
This is useful for local or staging environments.
Common pattern: guard clauses with debugging
if (!is_array($data)) {
$details = dump_to_string($data);
throw new InvalidArgumentException( . );
}
Common Mistakes
Mistake 1: Assigning var_dump() directly
Broken code:
$dump = var_dump($value);
Why it fails:
var_dump()prints output- it does not return the printed string
$dumpwill usually benull
Correct approach:
ob_start();
var_dump($value);
$dump = ob_get_clean();
Mistake 2: Forgetting to start buffering
Broken code:
var_dump($value);
$dump = ob_get_clean();
Why it fails:
- no output buffer was started
- the dump already went to the browser
Correct approach:
();
();
= ();
Comparisons
| Tool / Technique | Returns a string? | Prints directly? | Detail level | Common use |
|---|---|---|---|---|
var_dump() | No | Yes | High | Deep debugging |
print_r($value, true) | Yes | No, if second argument is true | Medium | Readable debugging |
var_export($value, true) | Yes | No | High | Exportable PHP representation |
json_encode() | Yes | No | Structured, JSON only |
Cheat Sheet
// Capture var_dump output to a string
ob_start();
var_dump($value);
$dump = ob_get_clean();
Key facts
var_dump()prints output directlyvar_dump()does not return the dump text- use output buffering to capture printed output
ob_start()begins bufferingob_get_clean()gets the buffer as a string and closes it
Reusable helper
function var_dump_to_string($value): string
{
ob_start();
var_dump($value);
return ob_get_clean();
}
Related alternatives
print_r($value, true); // readable string version
(, );
();
FAQ
How do I save var_dump() output in a variable in PHP?
Use output buffering:
ob_start();
var_dump($value);
$dump = ob_get_clean();
Why does var_dump() not return a string?
Because var_dump() is designed to print debugging information directly to output rather than return it.
Can I use print_r() instead of var_dump()?
Sometimes, yes. print_r($value, true) returns a string, but it does not include as much type detail as var_dump().
What is the difference between ob_get_clean() and ob_get_contents()?
ob_get_contents()reads the current buffer but leaves it active.ob_get_clean()reads the buffer and closes it.
Is capturing var_dump() output safe in production?
Mini Project
Description
Build a small PHP debugging helper that captures detailed variable output and writes it to a log file. This demonstrates how output buffering can turn var_dump() output into a reusable string for diagnostics.
Goal
Create a reusable function that captures var_dump() output and logs information about different variables.
Requirements
- Create a function that accepts any value and returns the
var_dump()output as a string. - Test the function with at least one array and one object.
- Write the captured output to a log file.
- Print a short success message to confirm the script ran.
- Keep the code valid PHP and runnable as a single script.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.