As you know var_dump()
in addition to value show its data type and length.
Is there any way to log its output to FireBug console?
I tried FirePHP and FireLogger but both output only value of a variable (sometimes even incorrect variable value).
Maybe what you need is something like this:
function var2console($var, $name='', $now=false)
{
if ($var === null) $type = 'NULL';
else if (is_bool ($var)) $type = 'BOOL';
else if (is_string ($var)) $type = 'STRING['.strlen($var).']';
else if (is_int ($var)) $type = 'INT';
else if (is_float ($var)) $type = 'FLOAT';
else if (is_array ($var)) $type = 'ARRAY['.count($var).']';
else if (is_object ($var)) $type = 'OBJECT';
else if (is_resource($var)) $type = 'RESOURCE';
else $type = '???';
if (strlen($name)) {
str2console("$type $name = ".var_export($var, true).';', $now);
} else {
str2console("$type = " .var_export($var, true).';', $now);
}
}
function str2console($str, $now=false)
{
if ($now) {
echo "<script type='text/javascript'>\n";
echo "//<![CDATA[\n";
echo "console.log(", json_encode($str), ");\n";
echo "//]]>\n";
echo "</script>";
} else {
register_shutdown_function('str2console', $str, true);
}
}
Usage: var2console($myvar, '$myvar');
or simply var2console($myvar);
It should very rarely be necessary to set the $now
parameter to true
, causing the immediate output of the <script>
tag. The advantage of using register_shutdown_function()
is that you don't need to pay attention to "where you are" in the HTML.
The json_encode()
preserves all characters in the transfer from PHP to JavaScript. The only caveat is about encoding: json_encode()
only works with UTF-8
(which is the recommended encoding in most cases, anyway). You may need something like utf8_encode()
or mb_convert_encoding()
if you use a different encoding (or rather, you may consider switching to UTF-8
).
The output to Firebug's console is simply the output of var_export()
, preceded by the type of the variable, including the length of strings and the count of arrays, and, optionally, by the name of the variable.
var_export()
provides a more readable output than var_dump()
. If you really need the output of var_dump()
, you can use something like this:
function dump2console($var, $name='', $now=false)
{
ob_start();
if (strlen($name)) {
echo "$name =\n";
}
var_dump($var);
$str = ob_get_clean();
str2console($str, $now);
}
Usage: dump2console($myvar, '$myvar');
or simply dump2console($myvar);
You should avoid circular references (var_dump()
detects them a step too late, and var_export()
doesn't detect them at all). This is how to do it, e.g., for $GLOBALS
:
function globals2console($now=false)
{
$g = $GLOBALS;
$g['GLOBALS'] = '(recursion)';
var2console($g, '$GLOBALS', $now);
}