I'm surprised I've never blogged this. Here's my "show" function I've used in PHP for a long time for debugging data structures. I have it right in my main file (dispatcher.php) so that it's always available.
<?php
function show($data, $func = "print_r", $return_str = false){
ob_start();
$func($data);
$output = '<pre>'.htmlspecialchars(ob_get_contents()).'</pre>';
ob_end_clean();
if($return_str) return $output; else echo $output;
}
?>
This way, I don't have to do things like:
<?php
echo '<pre>';
var_dump($data);
echo '</pre>';
?>
all the time, and can just say show($data, 'var_dump') instead. Moreover, the code example I just gave doesn't escape the output of var_dump(), so if you may have stuff that needs to be escaped for HTML you'll essentially have to type out the contents of my show() function above to correctly display it
.
The reason I'm blogging this now is because someone asked if he could see the source to my XML to PHP translator. I'm giving him an excerpt of it, and that excerpt contains show() (that's what actually prints everything if you run the translator). Here's a piece of that code:
<h2 id="xml">The original XML:</h2>
<?php show($f);?>
<h2 id="php">Resulting PHP data structure:</h2>
<?php show(XML_unserialize($f),$form->get('style'));?>
And, of course, that $form->get('style') bit is using my PHP form-processing library, Formation.
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):