Close
Write to the console in PHP

Write to the console in PHP

Last Updated on Wednesday 5th Oct 2022

PHP Console log

Here's the PHP helper function

php print console

			
					function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}

			
	

Use it like this

			
					debug_to_console("Test");
// Outputs like
Debug Objects: Test

			
	

phpkonsole

  • json_encode() to check if the variable type is unnecessary and add a buffer to solve problems with frameworks.
			
					function debug_to_console($data, $context = 'Debug in Console') {

    // Buffering to solve problems frameworks, like header() in this and not a solid return.
    ob_start();

    $output  = 'console.info(\'' . $context . ':\');';
    $output .= 'console.log(' . json_encode($data) . ');';
    $output  = sprintf('<script>%s</script>', $output);

    echo $output;
}

			
	
			
					$data = [ 'foo' => 'bar' ];
debug_to_console($data);`

			
	

php print to console

FireFox

  • On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console.
  • This is an addon to the awesome web development extension Firebug.

References