32

In PHP, I use json_encode() to echo arrays in HTML5 data attributes. As JSON requires - and json_encode() generates - values encapsulated by double quotes. I therefor wrap my data attributes with single quotes, like:

<article data-tags='["html5","jquery","php","test's"]'>

As you can see, the last tag (test's) contains a single quote, and using json_encode() with no options leads to parsing problems.

So I use json_encode() with the JSON_HEX_APOS parameter, and parsing is fine, as my single quotes are encoded, but I wonder: is there a downside doing it like this?

6
  • You mean downside in the meaning that it works? Commented Jan 12, 2012 at 9:18
  • 1
    I mean downside in the meaning of "unexpected side effects that hexadecimal encoding might produce" Commented Jan 12, 2012 at 9:24
  • You have not showed any code how you output something, so an answer could only be a good guess. Commented Jan 12, 2012 at 9:26
  • My question is more general than specific: I wonder, in general, what is involved in dealing with hexadecimal encoding. Commented Jan 12, 2012 at 9:36
  • 1
    @Jérémy It should work, as in, I can't off the top of my head think of a situation where it would not, but it's really the wrong thing to do. HTML escape any values that may break your HTML syntax, as simple as that. Commented Jan 12, 2012 at 9:39

2 Answers 2

59

You need to HTML escape data echoed into HTML:

printf('<article data-tags="%s">',
    htmlspecialchars(json_encode(array('html5', ...)), ENT_QUOTES, 'UTF-8'));
Sign up to request clarification or add additional context in comments.

3 Comments

+1 always use the appropriate encoding in output, the only way to go. Invalid code-points (like \x00 would need hex-encoding according to X(HT)ML specs).
for simplicity htmlspecialchars(json_encode($arrayData), ENT_QUOTES,'UTF-8')
i json_encode with htmlspecialchars(json_encode($arrayData), ENT_QUOTES,'UTF-8') how to decode?
13

or use the build-in option:

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

you can check it up in the manual: http://php.net/manual/en/json.constants.php#constant.json-hex-apos

1 Comment

Thank you very much. I did not know this option. It worked very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.