How to Escape single quotes in JSON encoded HTML5 data attributes

In this tutorial we gonna learn how to escape single quotes in JSON encoded HTML5 data attributes. This is very easy to understand.
Here is some basic info on HTML5 data attribute.

  • We can use these types of attributes to store custom data private to the page/application
  • We can embed custom data attributes
  • The data attribute name should not contain uppercase letters. The data attribute name starts with data-
  • So we can say that the prefix of every data attribute name is data-

Syntax:

<element_name data-attribute_name=”value_as_string“>

Escape single quotes in JSON encoded HTML5 data attributes

To escape single quotes, the best option is to use json_encode() to echo arrays in HTML5 data attributes.

We can also use a built-in. We will see that later. At first, check this out:

printf('<element_name data-attribute_name="%s">',
htmlspecialchars(json_encode(array('html5', ...)), ENT_QUOTES, 'UTF-8'));

Or you can simply use this one:

json_encode(array('html5', ...), JSON_HEX_APOS)

 

Leave a Reply

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