Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_encode json_decode UTF-8

Tags:

json

php

utf-8

How can I save a json-encoded string with international characters to the databse and then parse the decoded string in the browser?

<?php                $string = "très agréable";       // to the database      $j_encoded = json_encode(utf8_encode($string));      // get from Database      $j_decoded = json_decode($j_encoded);  ?>     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">     <?= $j_decoded ?> </html>  
like image 203
FFish Avatar asked Nov 02 '10 10:11

FFish


People also ask

What is json_encode and json_decode in PHP?

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 does the PHP function json_encode () do?

PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Parameters: $value: It is a mandatory parameter which defines the value to be encoded.

What is json_decode PHP?

The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.

How can access JSON decoded data in PHP?

PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);


2 Answers

json utf8 encode and decode:

json_encode($data, JSON_UNESCAPED_UNICODE)  json_decode($json, false, 512, JSON_UNESCAPED_UNICODE) 

force utf8 might be helpfull too: http://pastebin.com/2XKqYU49

like image 197
Lukas Liesis Avatar answered Oct 08 '22 21:10

Lukas Liesis


This is an encoding issue. It looks like at some point, the data gets represented as ISO-8859-1.

Every part of your process needs to be UTF-8 encoded.

  • The database connection

  • The database tables

  • Your PHP file (if you are using special characters inside that file as shown in your example above)

  • The content-type headers that you output

like image 21
Pekka Avatar answered Oct 08 '22 21:10

Pekka