How to encode url as javascript string in PHP generated HTML?
1 answer
json_encode
will work. You just need to use it correctly:
<a onclick="javascript:window.location.href=<?php echo htmlspecialchars(json_encode($url)); ?>">
This will work as it json_encode
already returns a quoted JavaScript expression. And htmlspecialchars
it is necessary to avoid possible HTML metacharacters.
+3
source to share