Print HTML code from JavaScript variable

Uncategorized

This also was about to drive me crazy so I will not let it go without writing about it..

Let’s say you have some long HTML code contained on a PHP variable, something like this

<?php
$some_div = '
<div id="box">
  <h1>Title</h1>
  <p>Article contents + comments</p>
<div>';
?>

Now you want to use this HTML code as a JavaScript variable instead of printing it directly, you will tell me you’ll do this:

<script type="text/javascript">
/* <![CDATA[ */
  var some_div = '<?php echo $some_div; ?>';
/* ]]> */
</script>

JavaScript doesn’t like unescaped new lines and special characters (mainly “, <  and >) too much, so the previous code won’t work, my quick solution for that is to do the following:

  • Encode the html code in PHP using urlencode
  • Decode it within JavaScript

When using PHP’s urlencode function, all whitespace characters will be replaced by + signs, so we’d better deal with those characters before encoding them, otherwise, we won’t make a difference between spaces and real + signs, please read the comment on the PHP code below to understand:

<?php

// replace consecutive white space characters with a single space
$some_div_2 = preg_replace('/s+/',' ',$some_div);

// Explode (cut the string on the white space and put the resulting part on an array)
$some_div_2 = explode(' ', $some_div_2);

// Encode the text contained on the array cells
foreach($some_div_2 as $index => $content)
  $some_div_2[$index] = urlencode($content);

// Implode (reassemble) the array to a string again
$some_div_2 = implode(' ', $some_div_2);

?>

<script type="text/javascript">
/* <![CDATA[ */

  // Import the variable from PHP
  var some_div = <?php echo $some_div_2; ?>

  // Decode it
  some_div_2 = unescape(decodeURI(some_div));

  // Display it
  document.writeln(some_div_2);

/* ]]> */
</script>

Leave a Reply

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