Question

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).

Was it helpful?

Solution

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);
}

OTHER TIPS

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:

reading cookie content from Firebug

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.

only from JavaScript a jquery From arrays in firebug and chrome is:

 console.dir('[object arrays]'); 

open the console and activate to F12... and write this code in console is the var_dump to php from jquery. array to json

var test = {"names":["john doe","JANE doe"],"ids":["123",null]}; console.dir(test);

if you need directly console fron PHP need a plugin

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top