php variable inside echo 'html code'

前端 未结 6 404
借酒劲吻你
借酒劲吻你 2020-11-28 16:12

I have php file index.php

In this file to use html code I am doing:

index.php

echo \'

                      
相关标签:
6条回答
  • 2020-11-28 16:36

    If you want to input/output large blocks of HTML with embedded variables you can simplify the process by using Heredocs:

    echo <<<_EOI_
    <div>
       <a class="fragment" href="$url">
    <div>
    _EOI_;
    

    You don't have to worry about escaping quotes, constant concatenation, or that ugly dropping in and out of <?php echo $var; ?> that people do.

    0 讨论(0)
  • You concatenate the string by ending it and starting it again:

    echo '
    <div>
    <a class="fragment" href="' . $url . '">
    <div>';
    

    Though I personally prefer to stop the PHP tags and start them again (if I have a lot of HTML) as my IDE won't syntax highlight the HTML as it's a string:

    ?>
        <div>
            <a class="fragment" href="<?php echo $url; ?>">link</a>
        </div>
    <?php
    
    0 讨论(0)
  • 2020-11-28 16:53

    if you are echoing php directly into html i like to do this

    <div><?=$variable?></div>
    

    much shorter than writing the whole thing out (php echo blah blah)

    if you are writing html in php directly then there several options

    $var = '<div>'.$variable.'</div>';   // concatenate the string
    $var = "<div>$variable</div>";       // let php parse it for you.  requires double quotes
    $var = "<div>{$variable}</div>";     // separate variable with curly braces, also requires double quotes
    
    0 讨论(0)
  • 2020-11-28 16:55

    Since you are printing several lines of HTML, I would suggest using a heredoc as such:

    echo <<<HTML
    <div>
    <a class="fragment" href="$url">
    <div>
    HTML;
    

    HTML can be anything as long as you use the same tag both in the beginning and the end. The end tag must however be on its own line without any spaces or tabs. With that said, specifically HTML also has the benefit that some editors (e.g. VIM) recognise it and apply HTML syntax colouring on the text instead of merely coluring it like a regular string.

    If you want to use arrays or similar you can escape the variable with {} as such:

    echo <<<HTML
    <div>{$someArray[1]}</div>
    HTML;
    
    0 讨论(0)
  • 2020-11-28 16:55

    Do it like

    <?php
    $url='http://www.stackoverflow.com';
    echo "<div><a class='fragment' href='$url' /></div>";
    
    0 讨论(0)
  • 2020-11-28 16:59

    If you want to maintain the echo statement you can do either

    echo '<a class="fragment" href="'.$url.'"><div>';
    

    or

    echo "<a class=\"fragment\" href=\"$url\">";
    

    The first is better for performances and IMHO is more readable as well.

    0 讨论(0)
提交回复
热议问题