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

1
2
3
4
5
6
7
<?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:

1
2
3
4
5
<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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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>

Further reading

Related links

Leave a Reply

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

*

* Copy this password:

* Type or paste password here:

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">