PHP Helpers: html_var_dump

With the last function being html_print_r this next one should come as no suprise, html_var_dump:

if ( !function_exists( 'html_var_dump' ) ) {
    function html_var_dump( $data ) {
        $out = "\n<pre class='html-var-dump'";
        $out .= " style='border: 1px solid #ccc; padding: 7px;'>\n";

        ob_start( );
        var_dump( $data );
        $out .= esc_html( ob_get_contents( ) );
        ob_end_clean( );

        $out .= "\n</pre>\n";

        return $out;
    }
}

Even though I tend to use print_r more often than var_dump, there are times where the type data that var_dump provides can be very helpful. Unfortunately var_dump will always display data, so it needed to be wrapped in a few output control functions ( ob_start, ob_get_contents, and ob_end_clean ) to capture it.

Related posts:

  1. PHP Helpers: debug_log
  2. PHP Helpers: html_print_r
  3. PHP Helpers: esc_html
  4. PHP Helpers: curl_http_request
  5. PHP Helpers: make_slug

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Comments »

 
  • Benjam says:

    Why not just set the return flag for var_export?

    $out .= var_export( $data, true );

    Or are var_dump and var_export too different for your tastes?

    And to aid in having to remember which vars go into which function, I wrap both in another function that chooses for me:

    if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings
    $var = print_r($var, true);
    }
    else {
    if ( ! function_exists('xdebug_disable')) {
    if (is_array($var) || is_object($var)) {
    $var = print_r($var, true);
    }
    else {
    $var = var_export($var, true);
    }
    }
    else {
    $var = var_export($var, true);
    }
    }

    that way, I always know what’s going on with my variables and it’s in the format I like. No confusion between an empty string and FALSE or NULL.

 

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>