php print variable to console code example

Example 1: php console log

// Assuming you are wishing to log to the JS Console...

<?php
	function consoleLog($msg) {
		echo '<script type="text/javascript">' .
          'console.log(' . $msg . ');</script>';
	}

	consoleLog('Hello, console!');
?>

Example 2: php console log

// A little correction / improvement to @Kaotik's answer:
<?php
	function consoleLog($msg)
	{
		echo '<script type="text/javascript">console.log('
          . str_replace('<', '\\x3C', json_encode($msg))
          . ');</script>';
	}

	consoleLog('Hello, console!');
?>

Example 3: php print to console

<script>
    console.log(<?= json_encode($foo); ?>);
</script>

Example 4: php console print

$a = array(
 null => 'a',
 true => 'b',
 false => 'c',
 0 => 'd',
 1 => 'e',
 '' => 'f'
);

echo count($a), "\n";

Tags:

Php Example