0

I am trying to read a file as a string and return it to the client to be executed as javascript code in order to save it as a variable. Like so

<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code=\'' . $codeAsString . '\'';
echo $script;
?>

Once returned, I want the variable code to have a string representation of the contents of target.js. However, it isn't working. I suspect it has to do with new line characters and single/double quotes... In Python they have a multi line quote

"""This
is
a "multi"
line
'quote'
"""

Is there anything like this in Javascript/php? I can't even wrap my head around whether I need the single quotes around $codeAsString when appending it to $script. Do I have to manually go in and prepend backslashes before all quotes, double quotes, back slashes...Surely they have helper functions for this

thanks.

0

2 Answers 2

1

json_encode is your friend...

<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code= '.json_encode($codeAsString) .';';
echo $script;
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! That worked almost flawlessly. Except instead of new lines, when I do console.log() I get these ghetto little carriage return symbols. Is this specific to Chrome, or does json_encode distinguish between new line and carriage return?
if I store it in var code and do console.log(code) the carriage returns are interpretted as new lines. If, however, I store it in an object for whatever reason {src : ''} and do console.log(code), now the src attribute of code has little carriage returns. Therefore, I suspect this is Chrome specific.
1

Use PHP function json_encode.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.