简体   繁体   中英

Outputting PHP string into a JS file causes syntax error

I'm trying to output a string into a JS file using PHP. Here's the PHP code

$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

$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.

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

$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

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.

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