How To Take JavaScript Code Inside PHP Variable?

By Faruque Ahamed Mollick

Hello, guys! I am here with a PHP code snippets which may be so amazing for you. In this tutorial, I will show you how to take complete JavaScript code inside PHP variable.

The below code is given as taking something inside PHP variable:

$myVariable = "This is variable text";

If you want a block of text or HTML code inside the PHP variable $myVariable, then the above code will works. But if you want to add JavaScrip code than in most of the cases the syntaxes will create the problem.There are some syntax in JavaScript

There are some syntaxes available in JavaScript which are also available in PHP. So sometimes you will see that the javaScript syntax act as PHP syntax at the middle of your JavaScript code. It will results in PHP error in most of the cases.

So what to do? How to solve this problem?

Don’t worry… I am going to give you the solution as I have started this article to solve the problem.

Proper way of taking JavaScript Code Inside PHP Variable

You can easily take JavaScript code inside PHP variable using the HEREDOC string method. See the below code how to do it:

$ad_code_pc = <<<EOD
Your JavaScript code will be here. You can also put text block and HTML code in this area.


Below is an example of this method:

$ad_code_pc = <<<EOD
<script id="exampleid" language="javascript">
   medianet_width = "728";
   medianet_height = "90";
   medianet_crid = "6855648654655";
   medianet_versionId = "58645649";
   (function() {
       var isSSL = 'https:' == document.location.protocol;
       var mnSrc = (isSSL ? 'https:' : 'http:') + '//' + (isSSL ? '&https=1' : '');
       document.write('<scr' + 'ipt type="text/javascript" id="mNSC" src="' + mnSrc + '"></scr' + 'ipt>');

Using the <<<EOD you can put JavaScript inside a PHP variable. You can even put text and HTML code also. But I am talking especially about JavaScript because this will create the problem in the “$myVariable = ‘JS CODE‘” structure.

So do you think this tutorial can solve your problem? Well, in my case it helps me in several times. Mostly in the time of putting Ad code dynamically inside PHP, this method is useful. First time I used this method at the time of putting the random ad between one of my blog’s each post content.


Leave a Reply

Your email address will not be published. Required fields are marked *