Sending “var_dump” to FireBug console

前端 未结 12 1230
忘掉有多难
忘掉有多难 2020-12-31 13:11

As you know var_dump() in addition to value show its data type and length.

Is there any way to log its output to

相关标签:
12条回答
  • 2020-12-31 13:27

    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;
    }
    
    0 讨论(0)
  • 2020-12-31 13:28

    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.

    0 讨论(0)
  • 2020-12-31 13:28

    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

    0 讨论(0)
  • 2020-12-31 13:32

    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);
    }
    
    0 讨论(0)
  • 2020-12-31 13:35

    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>
    
    0 讨论(0)
  • 2020-12-31 13:36

    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.

    0 讨论(0)
提交回复
热议问题