简体   繁体   中英

Proper way to escape json data in PHP without using JS comment hack

Consider the code below to send a json string to js from php,

<?php
    $str = "<!--<script>"; // This is from user input
?>

<script>
   var json_str = <?= json_encode($str) ?>;
</script>

The string will break the HTML, and the way to solve it is via something like the old school comment hack, eg

<script>
<!--
   var json_str = <?= json_encode($str) ?>;
//-->
</script>

Are there any alternative?

您可以使用标志JSON_HEX_TAG ,以便<>被编码为\<\>

json_encode($str, JSON_HEX_TAG)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM