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.
👋 Hi there! I'm Amit. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!