[英]PHP read and execute contents of a file as a string
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.我正在尝试将文件作为字符串读取并将其返回给客户端以作为 javascript 代码执行,以便将其保存为变量。 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.返回后,我希望变量
code
具有 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
我怀疑它与换行符和单/双引号有关......在 Python 他们有一个多行引号
"""This
is
a "multi"
line
'quote'
"""
Is there anything like this in Javascript/php? Javascript / php中有这样的东西吗? I can't even wrap my head around whether I need the single quotes around
$codeAsString
when appending it to $script
.在将 $codeAsString 附加到
$script
时,我什至无法理解是否需要在$codeAsString
周围加上单引号。 Do I have to manually go in and prepend backslashes before all quotes, double quotes, back slashes...Surely they have helper functions for this我是否必须手动输入 go 并在所有引号、双引号、反斜杠之前添加反斜杠......当然他们有帮助函数
thanks.谢谢。
json_encode is your friend... json_encode 是你的朋友...
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code= '.json_encode($codeAsString) .';';
echo $script;
?>
Use PHP function json_encode .使用 PHP function json_encode 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.