How can I capture the result of var_dump to a string?

后端 未结 13 1452
挽巷
挽巷 2020-11-27 08:39

I\'d like to capture the output of var_dump to a string.

The PHP documentation says;

As with anything that outputs its result directly to the

相关标签:
13条回答
  • 2020-11-27 09:24

    This maybe a bit off topic.

    I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.

    fwrite(fopen('php://stdout', 'w'), var_export($object, true));
    
    0 讨论(0)
  • 2020-11-27 09:30

    I really like var_dump()'s verbose output and wasn't satisfied with var_export()'s or print_r()'s output because it didn't give as much information (e.g. data type missing, length missing).

    To write secure and predictable code, sometimes it's useful to differentiate between an empty string and a null. Or between a 1 and a true. Or between a null and a false. So I want my data type in the output.

    Although helpful, I didn't find a clean and simple solution in the existing responses to convert the colored output of var_dump() to a human-readable output into a string without the html tags and including all the details from var_dump().

    Note that if you have a colored var_dump(), it means that you have Xdebug installed which overrides php's default var_dump() to add html colors.

    For that reason, I created this slight variation giving exactly what I need:

    function dbg_var_dump($var)
        {
            ob_start();
            var_dump($var);
            $result = ob_get_clean();
            return strip_tags(strtr($result, ['=>' => '=>']));
        }
    

    Returns the below nice string:

    array (size=6)
      'functioncall' => string 'add-time-property' (length=17)
      'listingid' => string '57' (length=2)
      'weekday' => string '0' (length=1)
      'starttime' => string '00:00' (length=5)
      'endtime' => string '00:00' (length=5)
      'price' => string '' (length=0)
    

    Hope it helps someone.

    0 讨论(0)
  • 2020-11-27 09:32

    Use output buffering:

    <?php
    ob_start();
    var_dump($someVar);
    $result = ob_get_clean();
    ?>
    
    0 讨论(0)
  • 2020-11-27 09:32

    You may also try to use the serialize() function. Sometimes it is very useful for debugging purposes.

    0 讨论(0)
  • 2020-11-27 09:36

    Here is the complete solution as a function:

    function varDumpToString ($var)
    {
        ob_start();
        var_dump($var);
        return ob_get_clean();
    }
    
    0 讨论(0)
  • 2020-11-27 09:38

    You could also do this:

    $dump = print_r($variable, true);
    
    0 讨论(0)
提交回复
热议问题