php实现echo json_encode正确显示汉字

时间:2023-03-09 01:35:26
php实现echo json_encode正确显示汉字
<?php
header('Content-type: text/html; charset=utf-8');
/*
function showmessage($msg = '', $redirect = '', $delay = 3){
if($_GET['format'] == 'json'){
$result = array('msg' => $msg, 'redirect' => $redirect, 'delay' => $delay);
echo json_encode($result);
exit();
}
include 'message.php';
exit();
} showmessage('helloworld','www.baidu.com',5);
*/
/*
$arr = array
(
'Name'=>'希亚',
'Age'=>20
); $jsonencode = json_encode($arr);
echo $jsonencode;
*/
$array = array
(
'title'=>iconv("GB2312","UTF-8//IGNORE",'这里是中文标题'),
'body'=>'abcd...'
); echo json_encode($array); $text = "This is the Euro symbol '€'."; echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
//echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;
/**************************************************************
*
* 使用特定function对数组中所有元素做处理
* @param string &$array 要处理的字符串
* @param string $function 要执行的函数
* @return boolean $apply_to_keys_also 是否也应用到key上
* @access public
*
*************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter > 1000) {
die('possible deep recursion attack');
}
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
} if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
} /**************************************************************
*
* 将数组转换为JSON字符串(兼容中文)
* @param array $array 要转换的数组
* @return string 转换得到的json字符串
* @access public
*
*************************************************************/
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
$array1 = array
(
'Name'=>'希亚',
'Age'=>20
);
$array = array
(
'Name'=>$array1,
'Age'=>20
); echo JSON($array);
?>