How to Escape String from PHP for JavaScript

Pass a PHP string to a JavaScript variable (and escape newlines)

Expanding on someone else's answer:

<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

How to escape text coming from PHP in JavaScript?

simply use json_encode:

var playlistacting = <?php echo json_encode($this->result);?>;

JS inside PHP Escape String (for functions)

  1. Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
  2. Every value have to be escaped properly, as explained in this article

So, for the JS values you have to escape them with json_encode() and, as they are going into HTML attribute, escape them as HTML too.

For the last element only HTML encoding is required.

foreach ($array as $element) 
{
$param1 = htmlspecialchars(json_encode($element[0])); // better give them
$param2 = htmlspecialchars(json_encode($element[1])); // meaningful names
$param3 = htmlspecialchars($element[2]);
?>
<a onClick="myFunctionTakesPHPValues(<?=$param1?>,<?=$param2?>)">
<?=$param3?>
</a>
<? }

And yes, using raw JS in HTML attributes considered as a bad practice.



Related Topics



Leave a reply



Submit