Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to return multi-line JavaScript code from PHP

Sometimes, you may wish to return multi-line JavaScript code from PHP along with some variables. For instance, a JavaScript object.

Here’s one way to do it.

$name = 'John Doe';
$age = 10;

echo '{ 
    "name": "'. $name .'", 
    "age": '. $age .' 
}';

As you can tell, the above code works but it’s not very readable, in my opinion. And with more variables, it will become even more difficult to read.

Well, today I learned there’s a better way to do this in PHP.

That is by using the heredoc syntax. The heredoc syntax is a way to declare strings in PHP. It starts with <<< followed by an identifier and then the string itself. The string then ends with the same identifier.

So, the above code can be written like so using the heredoc syntax.

$name = 'John Doe';
$age = 10;

echo <<<JAVASCRIPT
{ 
    "name": "$name", 
    "age": $age 
}
JAVASCRIPT;

Here, the identifier is JAVASCRIPT just to denote that the string is JavaScript code. You can use any identifier you want.

As you can tell, the above code is much more readable and straight-forward. The best thing about this is that you can use variables inside the heredoc syntax without any weird string concatenation.

By the way, I learned about this handy little snippet in the codebase of curlwind.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?