var_dump or print_r and html encoding

I found that knittl's code does not work. I had to make some small changes to get it to work as follows:

array_walk_recursive($inputarray, function(&$v) { $v = htmlspecialchars($v); });

Now this works fine in PHP5.3+


A function that works for me is described in this PHP manual comment.

His function that replaces var_dump is implemented as:

function htmlvardump()
{
    ob_start(); 
    $var = func_get_args(); 
    call_user_func_array('var_dump', $var); 
    echo htmlentities(ob_get_clean());
 } 

This works for me in PHP 5.3+.

(Please note that there was a typo in the original source).


While this question has an accepted answer, I think David Morrow's answer is the best/ simplest/ most practical (uses the print_r true flag):

echo "<pre>".htmlentities(print_r($some_array, true))."</pre>";

Never-the-less, here is another solution that uses output buffering:

<?php

ob_start();
print_r($some_array);
$buffer = ob_get_clean();
echo "<pre>".htmlentities($buffer)."</pre>";

?>

Or you could just save the print_r to a string and then escape it using the second parameter set to true.

$arr = array('<script>alert("hey");</script>');
$str = print_r($arr, true);
echo htmlentities($str);

outputs:

Array
(
   [0] => <script>alert("hey");</script>
)

script is not executed