简体   繁体   English

将PHP字符串输出到JS文件中导致语法错误

[英]Outputting PHP string into a JS file causes syntax error

I'm trying to output a string into a JS file using PHP.我正在尝试使用 PHP 将字符串输出到 JS 文件中。 Here's the PHP code这是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);";

I'm trying to write a JS file like so我正在尝试编写这样的 JS 文件

$fp = fopen("FOLDER/FILE.js", 'w');
fwrite($fp, $embedded_form_js);
fclose($fp);

The problem is that when I try to write the JS file, this error happens.问题是当我尝试编写JS文件时,会发生此错误。

syntax error, unexpected '(', expecting ']'

This is in reference to the line:这是参考线:

$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);

How can I remedy this?我该如何补救?

use Nowdocs as it is single-quoted and won't try to interpret the $_GET使用 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 http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

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

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