PHP中用echo输出JavaScript遇Parse error,如何添加单引号?
解决PHP echo输出含单引号的JavaScript代码时的解析错误
你猜的完全没错!这个解析错误就是因为单引号的冲突导致的。PHP里用单引号包裹字符串时,会把字符串内部的单引号当成当前字符串的结束标记——你写的echo 'document.write('<a ...>');里,document.write(后面的单引号会被PHP误判为这个echo字符串的结尾,后面的代码就变成了无效的PHP语法,自然抛出了Parse error。
下面给你几种简单的修复方案,任选其一都能解决问题:
方案1:转义字符串内部的单引号
在你要输出的单引号前加反斜杠\,告诉PHP这是一个普通字符,不是字符串结束符:
echo '<script type="text/javascript">'; echo 'document.write(\'<a style="display:block;width:100%;height:1px;" class="aff-ad-none"></a>\'); window.AFF_ONLOAD = window.AFF_ONLOAD || []; window.AFF_ONLOAD.push({lkid:"11",affid:"10",size:"728*90",type:"1",language:"English",web_id:"40",version:110}); var aff_s = document.createElement("script"),aff_h = document.getElementsByTagName("head")[0]; aff_s.charset = "utf-8";aff_s.async = !0; aff_s.src = "https://js.affasi.com/affasi_js.min.js"; aff_h.insertBefore(aff_s, aff_h.firstChild); </script>';
方案2:改用双引号包裹整个echo字符串
如果用双引号定义PHP字符串,内部的单引号不需要转义(但内部的双引号要转义),写法也很直观:
echo "<script type=\"text/javascript\">"; echo "document.write('<a style=\"display:block;width:100%;height:1px;\" class=\"aff-ad-none\"></a>'); window.AFF_ONLOAD = window.AFF_ONLOAD || []; window.AFF_ONLOAD.push({lkid:\"11\",affid:\"10\",size:\"728*90\",type:\"1\",language:\"English\",web_id:\"40\",version:110}); var aff_s = document.createElement(\"script\"),aff_h = document.getElementsByTagName(\"head\")[0]; aff_s.charset = \"utf-8\";aff_s.async = !0; aff_s.src = \"https://js.affasi.com/affasi_js.min.js\"; aff_h.insertBefore(aff_s, aff_h.firstChild); </script>";
方案3:用NOWDOC语法(推荐长代码场景)
对于这种较长的HTML/JS代码,用PHP的NOWDOC语法最省心,不需要频繁转义任何引号,代码可读性也更高:
echo <<<'EOT' <script type="text/javascript"> document.write('<a style="display:block;width:100%;height:1px;" class="aff-ad-none"></a>'); window.AFF_ONLOAD = window.AFF_ONLOAD || []; window.AFF_ONLOAD.push({lkid:"11",affid:"10",size:"728*90",type:"1",language:"English",web_id:"40",version:110}); var aff_s = document.createElement("script"),aff_h = document.getElementsByTagName("head")[0]; aff_s.charset = "utf-8";aff_s.async = !0; aff_s.src = "https://js.affasi.com/affasi_js.min.js"; aff_h.insertBefore(aff_s, aff_h.firstChild); </script> EOT;
注意:NOWDOC的结束标记EOT;必须单独占一行,而且不能有任何缩进。
内容的提问来源于stack exchange,提问作者stefanosn
相关产品推荐
相关产品推荐

