2

I have an array which one of the keys contains some HTML code. I am json_encoding this array for returning. I have recently noticed that json_encode() returns 'null' if the html contains special characters (ie: A méh virága).

How can I get json_encode() not to return 'null' if special accented characters are available?

David
  • 16,246
  • 34
  • 103
  • 162

2 Answers2

4

json_encode() assumes that text is in UTF-8 encoding. If the input looks like malformed UTF-8, it returns null. The only way to get json_encode() to work is to give it input in UTF-8 (which you should probably be using anyway).

And, as Zathrus Writer says in a comment, the actual PHP source code itself should probably also be in UTF-8 encoding, to prevent subtle bugs.

TRiG
  • 10,148
  • 7
  • 57
  • 107
  • So how does one give json_encode utf 8 input, when you have accented characters etc? – Andrew Feb 23 '18 at 19:23
  • Accented characters can be in many encodings, but UTF-8 is the only sensible one for most purposes. How you get there, though, depends on what you're doing. – TRiG Feb 23 '18 at 21:36
0

My answer, wrapped the html string with utf8_encode().

David
  • 16,246
  • 34
  • 103
  • 162
  • Playing around with character encodings without understanding what's breaking and why can fix things, but it's a dangerous way to go about it. – TRiG Sep 17 '12 at 10:27