Last active
August 29, 2015 13:56
-
-
Save strangecode/8875478 to your computer and use it in GitHub Desktop.
jsDump() - Log a PHP variable to javascript console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 <[email protected]> | |
*/ | |
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 <[email protected]> | |
*/ | |
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