Last active
September 27, 2017 23:54
-
-
Save schuyberg/312f5e6b8373ad24a0d85a9581226213 to your computer and use it in GitHub Desktop.
log to the JS console from PHP
This file contains hidden or 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
// use this anywhere in your php app | |
function console_log() { | |
$messages = func_get_args(); | |
if(!$GLOBALS['cLogs']){ | |
$GLOBALS['cLogs'] = array(); | |
} | |
$GLOBALS['cLogs'] = array_merge($GLOBALS['cLogs'], $messages); | |
} | |
// use this at the bottom of the global template (or wherever you can insert some js) | |
// probably worth adding a check for dev/prod env, ie. (strpos($env, 'dev') == -1) | |
function print_logs(){ | |
if (!$GLOBALS['cLogs']) { | |
return false; | |
} else { | |
echo "<script>"; | |
foreach($GLOBALS['cLogs'] as $k => $l) { | |
if (is_string($l)) { | |
echo "console.log('$l');"; | |
} else { | |
echo "console.log(" . json_encode($l, JSON_PRETTY_PRINT) . ");"; | |
} | |
} | |
echo "</script>"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment