将数组转换为 UTF-8 ?PHP JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12236459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:07:09  来源:igfitidea点击:

Convert arrays into UTF-8 ? PHP JSON

phparraysjson

提问by Silvio Marijic

i have multidimensional arrays generated by PHP with data from database ,but i have chars like "? ? ? ? ?" and when i try to output that in json he just returns null , i did some reading about that ,and it says that JSON is only working with UTF-8. So how can i convert those arrays in UTF-8 ? but i still need arrays at the and?

我有由 PHP 生成的多维数组,其中包含来自数据库的数据,但我有像“? ? ? ? ?”这样的字符。当我尝试在 json 中输出它时,他只返回 null ,我做了一些关于它的阅读,它说 JSON 只适用于 UTF-8。那么如何将这些数组转换为 UTF-8 呢?但我仍然需要数组和?

here is code of my script

这是我的脚本代码

     $sql_main = mysql_connect(DB_HOST, DB_UNM, DB_PSW);
    ($sql_main)? mysql_select_db(DB_NM) : mysql_error();

    $APP_URL_ACCESS = $_GET['app_access_key'];

    $sql_app = mysql_query("SELECT * FROM app_sys WHERE APP_OW_C='$APP_URL_ACCESS'") or die(mysql_error());

    if(mysql_num_rows($sql_app)==1){

        while($row = mysql_fetch_array($sql_app)){
        $APP_UA_ID          = $row['APP_UA_ID'];
        $APP_NM             = $row['APP_NM'];
        $APP_H_DMN          = $row['APP_H_DMN'];
        $APP_H              = $row['APP_H'];
        $APP_H_DB_UNM       = $row['APP_H_DB_UNM'];
        $APP_DB_NM          = $row['APP_DB_NM'];
        $APP_H_DB_PSW       = $row['APP_H_DB_PSW'];
        $APP_H_DB_SRV       = $row['APP_H_DB_SRV'];
        $APP_ACTIVE         = $row['APP_ACTIVE'];
        $APP_OW_C           = $row['APP_OW_C'];


    }
    $ROW_APP[] = array(
                        'APP_UA_ID' => $APP_UA_ID,
                        'APP_PERMISSION' => $APP_ACTIVE,
                        'APP_KEY' => $APP_OW_C);
    $APP_ARRAY[''] = $ROW_APP;



    ($APP_ACTIVE == '1')? $sql_connect_app = mysql_connect($APP_H_DB_SRV, $APP_H_DB_UNM, $APP_H_DB_PSW) && mysql_select_db($APP_DB_NM): $_MSG = "Application Is Not Active"; 

    $sql_news = mysql_query("SELECT * FROM news  ORDER BY id DESC LIMIT 10") or die(mysql_error());
    while($row = mysql_fetch_array($sql_news, MYSQL_ASSOC)){
            //$display_json['data'] = array(
                //'id' => $row['id'],
    //          'title' => $row['title'],
        //      'story' => $row['story'],
        //      'img' => $row['img'],
            //  'author' => $row['author'],
                //'datetime' => $row['datetime'],
                //'shorten_story' => substr($row['story'], 0, 150) . '...'); */

            $ROW_APP_DATA[] = $row; 
    //

}

$sql_news = mysql_query("SELECT * FROM actual  ORDER BY id DESC LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array($sql_news, MYSQL_ASSOC)){
        /*$display_json['data'] = array(
            'id' => $row['id'],
            'title' => $row['title'],
            'story' => $row['story'],
            'img' => $row['img'],
            'author' => $row['author'],
            'datetime' => $row['datetime'],
            'shorten_story' => substr($row['story'], 0, 150) . '...'); */
            $ROW_APP_THIRDPART[] = $row;    
    //

}

$JSON_ARRAY_APP['application'] = $ROW_APP;
$JSON_ARRAY_DATA_1['news'] = $ROW_APP_DATA;
$JSON_ARRAY_DATA_2['actual'] = $ROW_APP_THIRDPART;
$JSON_ARRAY_DATA['data'] = array_merge($JSON_ARRAY_DATA_1, $JSON_ARRAY_DATA_2);
$JSON_OUTPUT = array_merge($JSON_ARRAY_APP, $JSON_ARRAY_DATA);
echo json_encode($JSON_OUTPUT);

}else{
exit(); 
}

回答by WildlyInaccurate

I've found iconvto be the best method of converting a character set to UTF-8. You can make use of PHP's array_walk_recursiveto work with multidimensional arrays:

我发现iconv这是将字符集转换为 UTF-8 的最佳方法。您可以使用 PHParray_walk_recursive来处理多维数组:

$array = array(); // This is your multidimensional array

array_walk_recursive($array, function(&$value, $key) {
    if (is_string($value)) {
        $value = iconv('windows-1252', 'utf-8', $value);
    }
});

You can change windows-1252to whichever character set you're converting from.

您可以更改windows-1252为要转换的任何字符集。

回答by Cong Nguyen

Try this function:

试试这个功能:

function utf8_converter($array)
{
    array_walk_recursive($array, function(&$item, $key){
        if(!mb_detect_encoding($item, 'utf-8', true)){
            $item = utf8_encode($item);
        }
    });

    return $array;
}

回答by Arslan Tabassum

if multidimensional array, then use foreach loop and use this line inside foreach suppose

如果是多维数组,则使用 foreach 循环并在 foreach 中使用这一行假设

foreach ($your_array as $line){
   $line = array_map("utf8_decode", $line);    
}

回答by Jerry Chen

I met this problem as well and in 2016 you don't need to create a function, just use 'mb_convert_variables'

我也遇到了这个问题,在 2016 年你不需要创建一个函数,只需使用' mb_convert_variables'

mb_convert_variables('UTF-8', 'original encode', array or object)

mb_convert_variables('UTF-8', 'original encode', array or object)

For anyone who meet this situation, too.

对于任何遇到这种情况的人,也是。

回答by mixix

Try this PHP function where you simply pass in the array you wish encoded.

试试这个 PHP 函数,您只需传入您希望编码的数组即可。

function convertArrayKeysToUtf8(array $array) { 
$convertedArray = array(); 
foreach($array as $key => $value) { 
  if(!mb_check_encoding($key, 'UTF-8')) $key = utf8_encode($key); 
  if(is_array($value)) $value = $this->convertArrayKeysToUtf8($value); 

  $convertedArray[$key] = $value; 
} 
return $convertedArray; 
  } 

P.s check out php.net for other utf-8 encoding method ideas, but this has worked for me in the past.

Ps 查看 php.net 以了解其他 utf-8 编码方法的想法,但这在过去对我有用。

回答by Codebeat

$row = utf8_encode( $row );
convertUtf8ToHtml( $row );
$ROW_APP_DATA[] = $row;

See function below:


// converts a UTF8-string into HTML entities
    //  - $utf8:        the UTF8-string to convert
    //  - $encodeTags:  booloean. TRUE will convert '<' to '&lt;'
    //  - return:       returns the converted HTML-string
    function convertUtf8ToHtml(&$utf8, $encodeTags = false ) 
    {
        if( !is_string( $utf8 ) || empty( $utf8 ))
         { return false; }
        $result = '';
        for ($i = 0; $i < strlen($utf8); $i++) {
            $char = $utf8[$i];
            $ascii = ord($char);
            if ($ascii < 128) {
                // one-byte character
                $result .= ($encodeTags) ? htmlentities($char) : $char;
            } else if ($ascii < 192) {
                // non-utf8 character || not a start byte
            } else if ($ascii < 224) {
                // two-byte character
                $result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
                $i++;
            } else if ($ascii < 240) {
                // three-byte character
                $ascii1 = ord($utf8[$i+1]);
                $ascii2 = ord($utf8[$i+2]);
                $unicode = (15 & $ascii) * 4096 +
                           (63 & $ascii1) * 64 +
                           (63 & $ascii2);
                $result .= '&#$unicode;';
                $i += 2;
            } else if ($ascii < 248) {
                // four-byte character
                $ascii1 = ord($utf8[$i+1]);
                $ascii2 = ord($utf8[$i+2]);
                $ascii3 = ord($utf8[$i+3]);
                $unicode = (15 & $ascii) * 262144 +
                           (63 & $ascii1) * 4096 +
                           (63 & $ascii2) * 64 +
                           (63 & $ascii3);
                $result .= '&#$unicode;';
                $i += 3;
            }
        }

        $utf8 = $result;
        return true;
    }

回答by Wendy Funes

I don't use a function, I use the conversion in each assignment like:

我不使用函数,我在每个任务中使用转换,例如:

$APP_UA_ID = utf8_encode($row['APP_UA_ID']);