Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling special characters in json_encode

Tags:

json

php

In my database, there are many special characters like (İstanbul, Yeşilköy, Atatürk and more).

when I directly fetch these data from the database all working fine. Means data remain original but problem occur when I convert these data to JSON using json_encode().

After encoding all these data converted to some strange characters like ?stanbul, Bak?rköy...

But after decodeing (using json_decode) I need the original string which was before encoding(json_encode).

I tried many solutions provided on the web to solve the problem but none of them is fully working in my case.

some solutions I tried-

  • $item = utf8_encode($item);
  • $item = html_entity_decode($item, ENT_COMPAT, 'UTF-8');
  • http://www.php.net/manual/en/function.json-encode.php
  • I also tried a library available on github (https://github.com/neitanod/forceutf8)

If not possible to get the original string atleast there should not be any ? like thing(remove these things).

Suggest me something to solve the issue.

like image 525
Sunil Chhimpa Avatar asked Nov 29 '25 11:11

Sunil Chhimpa


2 Answers

Since PHP 5.4 you can use this :

json_encode($text, JSON_UNESCAPED_UNICODE);
like image 82
Saman Avatar answered Dec 02 '25 00:12

Saman


Use mysqli_set_charset(connection,charset); before mysqli_query();

Example:

mysqli_set_charset( $CONNECTION, "utf8" );

$result_query = mysqli_query( $CONNECTION, $query );
like image 38
Vishal Yadav Avatar answered Dec 02 '25 00:12

Vishal Yadav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!