doufengsui7449
2014-02-11 15:56
浏览 61
已采纳

php echo无需转义引号

Is there a way to 'echo' / 'render HTML' and not have to escape every quote?

Kind of like how below the HTML below is being rendered without having to use echo or escape anything.

disregard any php syntax errors, example only

 <? if($a == $b) {;?> I said: "It's with quotes" <? ;} ?>
 <? else {;?> They said "It's still with quotes" <? ;} ?>

the reason for this is I need to echo a large Javascript file that uses both single and double quotes, and it would take forever to escape them all.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • doumeng06063991 2014-02-11 15:59
    已采纳

    Assuming you're just trying to display (not run) some code, you can use any of these two approaches:

    • Store the JavaScript file as a separate file, and use file_get_contents() to get the code and display it in <pre> code-blocks
    • Use the HEREDOC syntax to store the file contents

    Approach #1:

    $contents = file_get_contents('file.js');
    echo '<pre>', $contents, '</pre>';
    

    Approach #2:

    $contents = <<<FILE
    
    ... contents ...
    
    FILE;
    
    echo '<pre>', $contents, '</pre>';
    

    I'd go with the first approach though. That way, you won't clutter up your script with long JavaScript code that's not actually used for page rendering. It's usually a good idea to separate your logic into multiple files. In both cases though, you don't have to worry about quoting, at all.

    打赏 评论
  • drqyxkzbs21968684 2014-02-11 16:00

    You can use the opposite type of quotes to delimit your strings:

    echo "It's with quotes";
    echo 'He said "Do it!"';
    

    You only have to escape quotes if they're the same as the ones used to delimit the string. So if you have both types of quotes in your string, you'll need to escape some of them:

    echo 'They said "It\'s still with quotes"';
    

    Another solution, usually used for long blocks, is heredoc:

    echo <<<EOF
    They said "It's still with quotes"
    EOF;
    
    打赏 评论
  • duanbiaojin8860 2014-02-11 16:00

    You can use HEREDOC syntax.

    $str = <<<TEXT
    I said: "It's with quotes"
    TEXT;
    

    The TEXT can be anything, as long as you use it on the opening line and the closing line:

    $str = <<<ANYTHING
    I said: "It's with quotes"
    ANYTHING;
    
    打赏 评论
  • duandangqin0559 2014-02-11 16:03

    You could use the so-called HEREDOC (pronounce here doc).

    Here is an example:

    $js = <<<JAVASCRIPT
    var some = {
        "javascript": 'here'
    };
    JAVASCRIPT;
    

    You don't need to escape anything, because you define named delimiters. In this case the delimiter is JAVASCRIPT. I suggest you read the whole documentation page and choose the best for your case. For example PHP 5.3+ provides the nice nowdoc syntax.

    打赏 评论

相关推荐 更多相似问题