Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using print_r in ob_start

Tags:

php

As mentioned in the manual it's not working. i tried var_dump it too suffers from the same problem.

ob_start()
$debugdata=print_r ($var,true)

This prints the result on screen than storing to a variable

like image 316
aWebDeveloper Avatar asked Feb 21 '23 10:02

aWebDeveloper


2 Answers

The second parameter of print_r is $return which allows the output to be returned as a string rather than outputting it:

$debugData = print_r($var, true);

There is no need to use output buffering for this, and in fact it cannot be used. You will need to end the output buffering before this and then restart the buffering after your print_r call:

ob_start();
// stuff
$output = ob_end_clean();

$debugData = print_r($var, true);

ob_start();
// more stuff
$output .= ob_end_clean();

EDIT: Another option is to nest output buffers and have an inner buffer do the print_r work:

ob_start(); // your original start  
// stuff

ob_start();
print_r($var);
$debugData = ob_get_clean();

// more stuff 
$output = ob_get_clean(); // your original end
like image 108
cmbuckley Avatar answered Mar 08 '23 02:03

cmbuckley


ob_start() starts outbut buffering. But you also need to end and retrieve the contents of the buffer as well.

Here are the functions you could use:

ob_get_clean() - puts the contents of the output buffer in a variable, ends and cleans the buffer.

ob_start();
print_r($foo);
$output = ob_get_clean();

ob_get_contents() - fetches the contents of the output buffer without closing or cleaning it.

ob_end_clean() - closes and cleans the buffer.

ob_start();
print_r($foo);
$output = ob_get_contents();
ob_end_clean();

There are a few other possibilities. Please make yourself familiar with the output buffering functions.

Also, a remark. You don't just assign the output of print_r to a variable. You just print stuff as if you were printing it on the screen. With output buffering on, all output will be buffered instead of being sent to stdout immediately. So, first you print_r, then retrieve the contents of the buffer.

[EDIT]

In the light of the conversation going on in the comments, I recommend having a look at the notes section of the print_r() manual. As @RomiHalasz and @cbuckley observe, due to print_r's internal output buffering, it cannot be used in conjunction with ob_start() while the second parametre, return, is used, as the two will collide.

You have to EITHER use output buffering and plain print_r (with only the first parametre), or end the output buffering before you use print_r with the second parametre.

Either this:

ob_start();
print_r($foo);
$output = ob_get_clean();

or this:

ob_start();
// blah
$output = ob_get_clean();

$output .= print_r($foo,true);

ob_start();
// blah
$output .= ob_get_clean();
like image 37
mingos Avatar answered Mar 08 '23 01:03

mingos