In javascript, I can print to the debug console using
console.log("Message here");
I'm now writing a php script, and would like to print to the debug console. Using the above code doesn't work in php. It seems I need to use either echo or some other command but I need the output to appear inside the output console, not the browser window.
This question is related to
php
This will work with either an array, an object or a variable and also escapes the special characters that may break your JS :
function debugToConsole($msg) {
echo "<script>console.log(".json_encode($msg).")</script>";
}
Edit : Added json_encode
to the echo
statement. This will prevent your script from breaking if there are quotes in your $msg
variable.
https://github.com/bkdotcom/PHPDebugConsole
Support for all the javascript console methods:
assert, clear, count, error, group, groupCollapsed, groupEnd, info, log, table, trace, time, timeEnd, warn
plus a few more:
alert, groupSummary, groupUncollapse, timeGet
$debug = new \bdk\Debug(array(
'collect' => true,
'output' => true,
'outputAs' => 'script',
));
$debug->log('hello world');
$debug->info('all of the javascript console methods are supported');
\bdk\Debug::_log('can use static methods');
$debug->trace();
$list = array(
array('userId'=>1, 'name'=>'Bob', 'sex'=>'M', 'naughty'=>false),
array('userId'=>10, 'naughty'=>true, 'name'=>'Sally', 'extracol' => 'yes', 'sex'=>'F'),
array('userId'=>2, 'name'=>'Fred', 'sex'=>'M', 'naughty'=>false),
);
$debug->table('people', $list);
this will output the appropriate <script>
tag upon script shutdown
alternatively, you can output as html, chromeLogger, FirePHP, file, plaintext, websockets, etc
upcomming release includes a psr-3 (logger) implementation
For something simple that work for arrays , strings , and objects I builed this function:
function console_testing($var){
$var = json_encode($var,JSON_UNESCAPED_UNICODE);
$output = <<<EOT
<script>
console.log($var);
</script>
EOT;
echo $output;
}
You can also try this way:
<?php
echo "<script>console.log('$variableName')</script>";
?>
<?php echo "<script>console.log({$yourVariable})</script>"; ?>
There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.
The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.
Source: Stackoverflow.com