PHP - Echoing multiple nested quotes of HTML

后端 未结 4 1266
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 18:13

I\'m attempting to echo the following line of HTML through PHP

echo \"

        
相关标签:
4条回答
  • 2021-01-26 18:39

    You need to do something like:

    echo "<a class='fa fa-ban fa-2x cancelClass' onClick=\"cancelClass('".$id."', '".$formattedDate."', '".$time."')\"></a><p class='text-center'>".$formattedDate." @ $time</p>";
    
    0 讨论(0)
  • 2021-01-26 18:56

    Using double quotes in HTML. Using htmlspecialchars with ENT_QUOTES to escape values which have double quote.

    echo '<a class="fa fa-ban fa-2x cancelClass" onClick="'.htmlspecialchars("cancelClass('$id', '$formattedDate', '$time')", ENT_QUOTES).
     '"></a><p class="text-center">'.$formattedDate." @ $time</p>";
    
    0 讨论(0)
  • 2021-01-26 18:59

    Change it to the following

    echo "<a class=\"fa fa-ban fa-2x cancelClass\" onClick=\"cancelClass('$id', '$formattedDate', '$time')\"></a><p class=\"text-center\">".$formattedDate." @ $time</p>";
    

    escaping the attribute double quotes you can have a normalized html

    0 讨论(0)
  • 2021-01-26 19:01

    They do get parsed properly, however you specified the wrong ones to use. Javascript can't differentiate between the quotes to wrap your string variables and the quotes to wrap the "onclick" value, it thinks the onclick ends too early.

    To differentiate them you'll have to escape them then. using \" for the ones inside the brackets.

    echo "<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass(\"$id\", \"$formattedDate\", \"$time\")'></a><p class='text-center'>".$formattedDate." @ $time</p>";
    

    should do the trick.

    Alternatively, don't use echo for the whole string, simply output most of it direct:

    ?> //temporarily stop interpreting the file as PHP, so the next bit will be output directly as raw HTML
    <a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass("<?php echo $id;?>", "<?php echo $formattedDate; ?>", "<?php echo $time;?>")'></a><p class='text-center'>".$formattedDate." @ $time</p>
    <?php //continue with PHP
    
    0 讨论(0)
提交回复
热议问题