Source: Tutorial: Log to Console in PHP
function console_log($data, $add_script_tags = false) {
$command = 'console.log('. json_encode($data, JSON_HEX_TAG).');';
if ($add_script_tags) {
$command = '<script>'. $command . '</script>';
}
echo $command;
}
Using PHP libraries to console log
If you want to outsource this logging middleware code to a helper Open Source library that allows more functionality, then you can look at something like PHPConsole or PHPDebugConsole.
PHPConsole is more popular on Github but is a little old, and less frequently updated. It works with a browser extension (for Chrome) to log information to the browser console. Code and installation instructions can be found here.
On the other hand, PHPDebugConsole, though it has only 34 stars on Github, is more frequently maintained and has better documentation. Code, installation information and usage instructions of the library can be found here.
By default, it outputs logs on the web-page in an organized fashion. Here is a usage example provided on their website that shows how easy it is to get started with logging using PHPDebugConsole.
<?php
require __DIR__.'/vendor/autoload.php'; // if installed via composer
// require 'path/to/Debug.php'; // if not using composer
$debug = new \bdk\Debug(array(
'collect' => true,
'output' => true,
));
$debug->log('hello world');
Below is an example of HTML output from their website.
They also provide support for logging to the browser’s console by installing certain extensions.
If you are working on a small scale personal project, in my opinion, nothing would match the simplicity of using your custom json_encode() based helper function. It would save you from taking care of the external dependencies and browser cross-compatibility.