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

后端 未结 13 1664
挽巷
挽巷 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: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.

提交回复
热议问题