开发者

PHP json_encode json_decode UTF-8

开发者 https://www.devze.com 2023-01-23 16:45 出处:网络
How can I save a json-encoded string with international characters to the databse and then parse the decoded string in the browser?

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&g开发者_如何学Got; 


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


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


  header('Content-Type: application/json; charset=utf-8');


If your source-file is already utf8 then drop the utf8_* functions. php5 is storing strings as array of byte.

you should add a meta tag for encoding within the html AND you should add an http header which sets the transferencoding to utf-8.

<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

and in php

<?php
header('Content-Type: text/html; charset=utf-8');


Try sending the UTF-8 Charset header:

<?php header ('Content-type: text/html; charset=utf-8'); ?>

And the HTML meta:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


  1. utf8_decode $j_decoded = utf8_decode(json_decode($j_encoded)); EDIT or to be more correct $j_encoded = json_encode($j_encoded); $j_decoded = json_decode($j_encoded); no need for en/decoding utf8
  2. <meta charset="utf-8" />


For me both methods

<?php

header('Content-Type: text/html; charset=utf-8');

echo json_encode($YourData, \JSON_UNESCAPED_UNICODE);


if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json. You can either remove the first character or save if without BOM.


Work for me :)

function jsonEncodeArray( $array ){
    array_walk_recursive( $array, function(&$item) { 
       $item = utf8_encode( $item ); 
    });
    return json_encode( $array );
}


I had the same problem. It might differ depending on how You put the data to the db, but try what worked for me:

$str = json_encode($data);
$str = addslashes($str);

Do this before saving data to db.

0

精彩评论

暂无评论...
验证码 换一张
取 消