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)
- Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
- 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
PHP Check If Time Is Between Two Times Regardless of Date
How to Use Composer to Autoload Classes from Outside the Vendor
Execute Two Shell Commands in Single Exec PHP Statement
How to Prevent JavaScript Code Theft
Global Variables in PHP Not Working as Expected
Codeigniter 2 on Iis with Web.Config File
Bulk Rename Files in a Folder - PHP
Utf-8 in PHP Regular Expressions
Split an Array into N Arrays - PHP
Accented Characters in MySQL Table
How to Execute PHP Code in a Sandbox from Within PHP
Stdclass Object and Foreach Loops
How to Display PHP Errors in Code Output
How to Cause a Redirect to Occur Before PHP Script Finishes
Symfony 2 Load Different Template Depending on User Agent Properties