dongpu2727 2011-07-14 19:28
浏览 39
已采纳

PHP以字符串形式读取和执行文件的内容

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.

  • 写回答

2条回答 默认 最新

  • dongshi6528 2011-07-14 19:31
    关注

    json_encode is your friend...

    <?php
    $fileName = 'target.js';
    $codeAsString = file_get_contents($fileName);
    $script = 'var code= '.json_encode($codeAsString) .';';
    echo $script;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?