我试图使用PHP将字符串输出到JS文件中。这是PHP代码
$embedded_form_js = "document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);";
我试图写一个像这样的JS文件
$fp = fopen("FOLDER/FILE.js", 'w');
fwrite($fp, $embedded_form_js);
fclose($fp);
问题在于,当我尝试编写JS文件时,会发生此错误。
syntax error, unexpected '(', expecting ']'
这是参考这一行:
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
我该如何解决这个问题?
答案 0 :(得分:0)
使用Nowdocs,因为它是单引号,不会尝试解释$ _GET
$embedded_form_js = <<<'EOS'
document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);
EOS;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc