Using PHP Strings in JavaScript

2:02 pm PHP

Here's a little something I came up with today for dealing with strings being moved from PHP into JavaScript code. The problem is that if you have some sort of textual content in your PHP script (perhaps the result of a "screen-scraping" operation), if you try to directly use it within some JavaScript being output to your page, you'll run into all sorts of headaches due to newlines, quotes, etc. For instance, the following will not work:

<?php
$html file_get_contents('http://www.charles-reace.com');
echo <<<END
<script type='text/javascript'>
var htmlText="$html";
document.write(htmlText);
</script>
END;
?> 

But, we can urlencode the text on the PHP side, converting all those problematic characters into the encoded form. Then we can decode it in JavaScript via its unescape() function. On the PHP side we need to use rawurlencode rather than just urlencode(), as the latter replaces spaces with "+" characters, but the JavaScript unescape() does not convert them. Now we can change our test script to:

<?php
$html file_get_contents('http://www.charles-reace.com');
$encoded rawurlencode($html);
echo <<<END
<script type='text/javascript'>
var htmlText="$encoded";
document.write(unescape(htmlText));
</script>
END;
?> 

Now the page generates no JavaScript errors and outputs the text as expected.

Leave a Comment

Note: You must be registered and logged in in order to leave a comment.