PHP - Echoing multiple nested quotes of HTML

本小妞迷上赌 提交于 2019-12-02 19:17:24

问题


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

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

I don't get an error. But the quotes for onClick='cancelClass... don't get parsed properly, which leads to the javascript function not executing.

How it gets color coded in Google Chrome Source View

How it should get color coded (example of another function)


回答1:


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




回答2:


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>";



回答3:


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



回答4:


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>";


来源:https://stackoverflow.com/questions/44949741/php-echoing-multiple-nested-quotes-of-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!