Double quotes or single quotes inside html tag, which one is the better?

If you google “Double quotes or single quotes inside html tag, which is better”, you might hear someone is talking about using double quotes in html won’t pass XHMTL validation. I think it is nonsense.

Both of these characters are valid for XHTML, i.e. both

<tag att="value">

and

<tag att='value' >

are valid. However, I have a good reason to encourage you to stick to double quotes.

When value is taken from user input, it is a must to convert all applicable characters to HTML entities by htmlentities(), and htmlentities() default flag is ENT_COMPAT which convert double quotes but leave single quotes alone. That is to say,

If I use

<tag att="(value taken from user input)">

constantly in templates, and if htmlentities() converts all double quotes in user input, whatever user input is, it will not break html output.

I used to use double quotes and single quotes interchangeably, but I learned from Magento. Magento sticks to using double quotes. Its htmlEscape() bridges to htmlspecialchars() but it does not let you pass in a flag to control how to convert double quotes or single quotes. So, if you use

<tag att='(value taken from user input)'>

, and if you rely on Magento htmlEscape() to convert special charcters for you, when user input has some single quotes, it ruins html output. I am sure you do not want it happens, so stick to using double quotes, always.

Leave a comment

Your email address will not be published. Required fields are marked *