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).
The function var_dump() displays structured information (type and value) about one or more expressions/variables. Arrays and objects are explored recursively with values indented to show structure. All public, private and protected properties of objects will be returned in the output.
The var_dump equivalent in JavaScript? Simply, there isn't one. Prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM tab.
var_dump() displays values along with data types as output. print_r() displays only value as output. It does not have any return type. It will return a value that is in string format.
It's too simple. The var_dump() function displays structured information about variables/expressions including its type and value. Whereas The print_r() displays information about a variable in a way that's readable by humans. Example: Say we have got the following array and we want to display its contents.
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);
}
You can dump JavaScript to the console by putting a console.log() in a script tag:
<script type="text/javascript">
console.log("hello");
</script>
So if you do a php dump in there...
<script type="text/javascript">
console.log("<?php var_dump('abc'); ?>");
</script>
You just need to be careful about ' and " in the var_dump breaking your JavaScript. In this example it will be ok because the HTML would be:
<script type="text/javascript">
console.log("string 'abc' (length=3)");
</script>
Just remember the php is processed then put in the JavaScript. You could also dump it to a comment:
<!--
<?php
var_dump('abc');
?>
-->
Then you can view source, or inspect element.
<script>console.log( <?= json_encode( $var ) ?> )</script>
Just throwing my hat in the ring. It sounds like FirePHP is the best way to go.
FirePHP does the job well + you can use it while you're developing Ajax.
Sample code:
require_once('FirePHPCore/fb.php'); # add the library
fb($var); #log the variable
fb( var_export($var,true) ); # log the variable with the var_export format
If you're passing an array to it, you can click it from your console and it will open a popup on your screen. You can even expand/collapse arrays and objects.
EDIT:
If you're looking for data types and length, use var_dump()
.
fb( var_dump( array(
1,
'a',
true
) ) );
I always use this script in combination with Zend_Log_Writer_Firebug (using firephp http://www.firephp.org/), because after redirects in the applicaton or ajax requests debugging with xdebug does not always work as expected:
require_once '/Zend/Log.php';
require_once '/Zend/Log/Writer/Firebug.php';
require_once '/Zend/Controller/Response/Http.php';
require_once '/Zend/Controller/Request/Http.php';
// create the logger and log writer
$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);
// get the wildfire channel
$channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();
// create and set the HTTP response
$response = new Zend_Controller_Response_Http();
$channel->setResponse($response);
// create and set the HTTP request
$channel->setRequest(new Zend_Controller_Request_Http());
// record log messages
$logger->info('test');
$logger->info(var_export($_SESSION,true));
$logger->info(count(var_export($_SESSION,true)));
$logger->info(strlen(var_export('hello',true)));
$logger->info(get_type($_SESSION,true));
// insert the wildfire headers into the HTTP response
$channel->flush();
// send the HTTP response headers
$response->sendHeaders();
You can build your own library to get the type of a variable:
<?php
function get_type($var)
{
if(is_object($var))
return get_class($var);
if(is_null($var))
return 'null';
if(is_string($var))
return 'string';
if(is_array($var))
return 'array';
if(is_int($var))
return 'integer';
if(is_bool($var))
return 'boolean';
if(is_float($var))
return 'float';
if(is_resource($var))
return 'resource';
//throw new NotImplementedException();
return 'unknown';
}
?>
Using a function call to var_dump_ret as argument for $logger->info() might be helpful, too. I haven't tested it yet.
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
if you just want to see the var_dump
out put in the firebug (client side) without doing any things in Javascript I would recommande using cookies following is an illustration how you can perform it that way:
<?php
$str = "Abu Romaïssae";
sendVarDumpToFront($str);
echo "<pre>";
echo $str."\n";
function sendVarDumpToFront( $mixed ){
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
setcookie("var_dump",$content);
}
than you can have it in firebug this way:
IMPORTANT
since this way uses cookies you will have to put the var_dump content before outputing any content otherwise this will not work
From: http://sixrevisions.com/web-development/how-to-debug-php-using-firefox-with-firephp/
Fb::log($array, "dumping an array")
That will get you the type and data. You'll have to do extra logging manually for length/count.
The following will take anything from var_dump() and encode it in JSON before attempting to send it to console.log(). This prevents and special characters from messing up the output.
<?php
$myArray = array('Red','Green','Blue','Orange','Yellow','Purple');
ob_start();
var_dump($myArray);
$var_dump = ob_get_contents();
ob_end_clean();
?>
<script>
var var_dump = <?php echo json_encode($var_dump); ?>;
console.log(var_dump);
</script>
If you have an Ajax (XHR) call that is generating output with a var_dump() then you can inspect the request in FireBug either under 'Console' or 'Net'. Click the plus sign to expand it and look at the 'Response' tab.
Otherwise if you are putting var_dump() into the main page you are viewing it should just appear in the page as viewed although the formatting might be messed up. Try
echo '<PRE>'
before the var_dump() or alternatively view the page source rather than the direct output.
I think one easy way to achieve this goal is to do a simple
console.log(<?php var_export($var, true) ?>);
You are over complicating what is a simple issue. Firebug (and any other console/dom log viewer is for viewing client side output. PHP being server side and doesn't make much sense pushing to the console log.
With that said, if you REALLY wanted to pipe a server-side output to the console log you should convert that output into json and pass it onto the console log. If you simply want to output variable values on a life site without people knowing that you are working on it (and you shouldn't be working on a live version anyway but that's beside the point) why not pipe the output to a file and read that output however you like, you could even use ajax to pass the dump off to the log via jquery.
The point I am trying to make is...you are over-complicating what you are trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With