[英]How to convert php array to utf8?
我有一個數組:
require_once ('config.php');
require_once ('php/Db.class.php');
require_once ('php/Top.class.php');
echo "db";
$db = new Db(DB_CUSTOM);
$db->connect();
$res = $db->getResult("select first 1 * from reklamacje");
print_r($res);
我想將它從 windows-1250 轉換為 utf-8,因為我有像
最好。
$utfEncodedArray = array_map("utf8_encode", $inputArray );
完成工作並返回一個帶有數字鍵的序列化數組(不是關聯)。
array_walk(
$myArray,
function (&$entry) {
$entry = iconv('Windows-1250', 'UTF-8', $entry);
}
);
在 PDO 連接的情況下,以下可能會有所幫助,但數據庫應為 UTF-8:
//Connect
$db = new PDO(
'mysql:host=localhost;dbname=database_name;', 'dbuser', 'dbpassword',
array('charset'=>'utf8')
);
$db->query("SET CHARACTER SET utf8");
有一個簡單的方法
array_walk_recursive(
$array,
function (&$entry) {
$entry = mb_convert_encoding(
$entry,
'UTF-8'
);
}
);
你可以使用這樣的東西:
<?php
array_walk_recursive(
$array, function (&$value)
{
$value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
);
?>
您可以將數組發送到此函數:
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;
}
這個對我有用。
以前的答案對我不起作用:(但是這樣也可以:)
$data = json_decode(
iconv(
mb_detect_encoding($data, mb_detect_order(), true),
'CP1252',
json_encode($data)
)
, true)
您可以使用string utf8_encode( string $data )
函數來完成您想要的。 它用於單個字符串。 您可以編寫自己的函數,使用該函數可以在 utf8_encode 函數的幫助下轉換數組。
由於這篇文章是一個不錯的SEO站點,所以我建議使用內置函數“ mb_convert_variables ”來解決這個問題。 它使用簡單的語法。
mb_convert_variables('utf-8', 'original encode', array/object)
對數組進行編碼的更通用函數是:
/**
* also for multidemensional arrays
*
* @param array $array
* @param string $sourceEncoding
* @param string $destinationEncoding
*
* @return array
*/
function encodeArray(array $array, string $sourceEncoding, string $destinationEncoding = 'UTF-8'): array
{
if($sourceEncoding === $destinationEncoding){
return $array;
}
array_walk_recursive($array,
function(&$array) use ($sourceEncoding, $destinationEncoding) {
$array = mb_convert_encoding($array, $destinationEncoding, $sourceEncoding);
}
);
return $array;
}
您可以執行以下操作,而不是使用遞歸來處理可能很慢的多維數組:
$res = json_decode(
json_encode(
iconv(
mb_detect_encoding($res, mb_detect_order(), true),
'UTF-8',
$res
)
),
true
);
這會將任何字符集轉換為 UTF8 並保留數組中的鍵。 因此,您可以一次性完成整個結果集,而不是使用array_walk
來“懶惰”地轉換每一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.