Skip to content

Instantly share code, notes, and snippets.

@strangecode
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strangecode/8875478 to your computer and use it in GitHub Desktop.
Save strangecode/8875478 to your computer and use it in GitHub Desktop.
jsDump() - Log a PHP variable to javascript console.
<?php
// Somewhere in your code…
jsDump($var1, 'var1', __FILE__, __LINE__); // TODO: remove me for production.
jsDump($var2, 'var2', __FILE__, __LINE__); // TODO: remove me for production.
?>
<?php
/*
* Log a PHP variable to javascript console. Relies on getDump(), below.
*
* @access public
* @param mixed $var The variable to dump.
* @param string $prefix A short note to print before the output to make identifying output easier.
* @param string $file The value of __FILE__.
* @param string $line The value of __LINE__.
* @return null
* @author Quinn Comendant <quinn@strangecode.com>
*/
function jsDump($var, $prefix='jsDump', $file='-', $line='-')
{
if (!empty($var)) {
?>
<script type="text/javascript" charset="utf-8">
/* <![CDATA[ */
window.console && console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
/* ]]> */
</script>
<?php
}
}
/*
* Return a string version of any variable, optionally serialized on one line.
*
* @access public
* @param mixed $var The variable to dump.
* @param bool $serialize If true, remove line-endings. Useful for logging variables.
* @return string The dumped variable.
* @author Quinn Comendant <quinn@strangecode.com>
*/
function getDump($var, $serialize=false)
{
ob_start();
print_r($var);
$d = ob_get_contents();
ob_end_clean();
return $serialize ? preg_replace('/\s+/m', ' ', $d) : $d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment