Tutorial :How to assign HTML as a variable value in PHP?


My goal is to store some html-formatted data in a variable, then echo it later.

For example:

<?php   $foo = '<div id="x">';  echo $foo;  ?>  

The above doesn't work. Why?


Sorry for the bad question. I thought it didn't work because nothing is visible when viewed in a browser. Of course nothing is visible because there is only a div and no text. Doh! My "real life" version of the above script was broken due to an extra apostrophe.


It probably works, but you're not seeing it because it's in the source code and not displayed visually on the web page.

Are you looking to actually display the source code in the web page? If so you will need to turn the < and > characters into &lt; and &gt; with htmlspecialchars.


I don't see what wouldn't work in your example (unless stackoverflow mangled some of your characters). You're alternating the quotes. On the other hand, you didn't say what doesn't work. Is it a compile error or nothing is printed, or...?

does this work?

$foo = "<div id=\"x\">";  

if there's a fair amount of html text, take a look at heredoc syntax.

$name = 'MyName';    echo <<<EOT  My name is "$name". I am printing some $foo->foo.  Now, I am printing some {$foo->bar[1]}.  This should print a capital 'A': \x41  EOT;  


$mytext = <<<EOT  ... a bunch of html text here ...  EOT;  


Works fine for me. The error must be somewhere else, check the error log?


<?php   $foo = '<div id="x">something</div>';  echo $foo;  ?>  

works for me. You did not close your div.


<div>  <?php $chatid ="<div id='chatid'></div>";   echo $chatid;    ?>  </div>        <script>  function chatuser(id)  {  document.getElementById("chatid").innerHTML= id;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »