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.