Print HTML code from JavaScript variable

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

# define the $html variable using the
# Nowdoc syntax to avoid parsing

$html = <<<'HTML'
<div id="box">
  <h1>Title</h1>
  <p>Article contents + comments</p>
</div>
HTML;

# Warning: no spaces before or after "HTML;"

?>

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 html = <?php echo $html; ?>
/* ]]> */
</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:

<?php

$html2 = preg_replace('/\s+/',' ',$html);

$html2 = explode(' ', $html2);

foreach($html2 as $index => $content)
  $html2[$index] = urlencode($content);
$html2 = implode(' ', $html2);
?>

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

  // Import the variable from PHP
  var html = <?php echo $html2; ?>

  // Decode it
  unescape(decodeURI(html2));

  // Display it
  document.writeln(html2);

/* ]]> */
</script>

Leave a Reply