How to Print JavaScript Console Using PHP

In this snippet, we will demonstrate how PHP echo can be used for printing JavaScript console. Generally, it is used for printing values to the HTML document. To print to the console, you can apply the <script> tag within the echo command.

Below, you can find several examples for different circumstances.

Watch a course Learn object oriented PHP

Using echo Keyword to Display Content

For displaying content with the help of the echo keyword, you should run the code below:

<?php

// Declaring variable and storing the string
$var1 = "W3docs";
$var2 = "A programming portal";

// Use echo keyword to display result
echo $var1 . "\n" . $var2;

?>

The output will look like this:

  W3docs
  A programming portal

As you can see, the Dot (.) operator is applied to combine two strings in PHP. The echo keyword is applied for displaying the values of variables$ var1 and $var2 to the HTML document that the browser can read normally.

So, you can write the JavaScript code in the echo section, then take it to the HTML document.

Printing a String into the Console

In this section, we will illustrate how to print a string into the console.

Here is an example:

<?php

// Use echo keyword to display result
echo "Open console and check";

echo '<script>console.log("Welcome to W3docs!");</script>';

?>

Printing PHP Variables Value to the Console

To print PHP variables value to the console, you can run the following code:

<?php

// Declare variable and store the string
$var1 = "W3docs";
$var2 = "A computer science portal";

echo "Open console and check";

echo '<script>console.log(`' . $var1 . "\n" . $var2 . '`); </script>';

?>

What is PHP echo

Actually, echo is not considered a function. It is rather a language construct. Hence, parentheses may not be used with it.

It is essential to note that echo can’t always be applied in the context of a function.

Once, it is necessary to pass more than one parameter to it, then you shouldn’t enclose those parameters within parentheses.