Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping JSON apostrophe before PHP's json_encode truncates?

Tags:

json

php

getjson

I have a field in a MySQL database (utf8_general_ci) that contains a curly (smart?) apostrophe: Owner’s...

This prints fine with no special handling if I access the PHP page that pulls it from the DB. However, I am trying to access it via a $.getJSON request on another page, so I used PHP's json_encode. It truncates the value so that it reads Owner, then successfully encodes the rest of the data. If I use PHP's utf8_encode on the field before I json_encode, it includes the full value with the encoded to \u0092 which then doesn't print anything on the page, giving me Owners. PHP's htmlentities and htmlspecialchars have no effect.

Looking at the request in Chrome's tools, Owner’s is shown as Owner�s on the $.getJSON page.

Can anyone help me out here? I have read other questions on SO and the web but I cannot find anything that helps and I haven't worked much with JSON.

Thanks for reading.

like image 505
Sarah Kemp Avatar asked Feb 26 '13 19:02

Sarah Kemp


People also ask

What does JSON_ encode do?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What is json_encode in JavaScript?

The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable. We demonstrate on this page with single level arrays. Other pages demonstrate using json_encode with multi-dimensional arrays and scalar values.

What is Json_unescaped_unicode?

JSON_UNESCAPED_UNICODE (int) Encode multibyte Unicode characters literally (default is to escape as \uXXXX).


2 Answers

For details: json_encode

Example:

echo json_encode($array, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
like image 87
itsazzad Avatar answered Oct 06 '22 00:10

itsazzad


Using PHP's utf8_encode() before my json_encode() did indeed stop the data from cutting off after the but it also encoded it to \0092 which did not display (control character). When I used MySQL's SET NAMES utf8 before my query, I did not have to use utf8_encode() at all, and my json was encoded correctly with mapping to \u2019, which displays nicely.

Thanks for the link @Pekka, it helped me narrow down the possibilities.

like image 39
Sarah Kemp Avatar answered Oct 05 '22 23:10

Sarah Kemp