Escape double quotes with variable inside HTML ech

2019-01-20 07:29发布

This question already has an answer here:

For a variable inside a echo that contains HTML, where would I add slashes to escape the double quotes?

Example:

echo "<input type=\"hidden\" name=\"id\" value=".$row['id']." />";

This part:

value=".$row['id']."

3条回答
Explosion°爆炸
2楼-- · 2019-01-20 07:41

Some tips on outputting HTML with PHP:

  1. Use single quotes so that you don't have to escape the double quotes (when using echo),
  2. Use htmlspecialchars() to properly escape any "rogue" values you may have.

Example using echo:

echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';

Or printf():

printf('<input type="hidden" name="id" value="%s" />', 
    htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8')
);

Or, in HTML mode:

?>
<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>" />
<?php
查看更多
疯言疯语
3楼-- · 2019-01-20 07:46

Use htmlentities:

echo "<input type=\"hidden\" name=\"id\" value=\"".htmlentities($row['id'])."\" />";
查看更多
何必那么认真
4楼-- · 2019-01-20 08:07

How about use single quotes so you don't have to escape any quotes. Like so:

echo '<input type="hidden" name="id" value="'.$row['id'].'" />';
查看更多
登录 后发表回答