简体   繁体   English

无需使用JS注释hack即可在PHP中转义json数据的正确方法

[英]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向js发送json字符串,

<?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 该字符串将破坏HTML,而解决该问题的方法是通过诸如旧学校注释hack之类的方法,例如

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

Are there any alternative? 还有其他选择吗?

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

json_encode($str, JSON_HEX_TAG)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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