作者yuffy0327 (魚排)
看板PHP
標題[請益] 從PHP往SQL撈資料, 無法顯示中文
時間Tue Dec 10 18:01:20 2013
以下這是一段來自網路的Sample code, 試過很多種方法都無法顯示中文
1. 在PHP裡
echo '<meta http-equiv="Content-Type" content="text/html" charset="big5" />';
2. 在PHP外
<meta http-equiv="Content-Type" content="text/html" charset="big5" />
上述方法都試過用utf8來寫, 資料庫的編碼為"utf8_general_ci"
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 163.21.79.182
1F:→ yuffy0327:還請各位幫忙了OTZ 12/10 18:02
2F:→ JustGame:資料庫是 utf8,但是 charset 卻是 big5? 12/10 22:24
3F:→ Bambe:你要不要先用phpmyadmin撈資料出來中文有沒有正確顯示? 12/10 23:19
4F:→ yuffy0327:回JustGame: 我兩種都試過了, 不論是utf8還是big5 12/10 23:41
5F:→ yuffy0327:回Bambe: 我下過Select*, 是可以正常顯示中文的 12/10 23:42
6F:→ yuffy0327:在想是不是json_encode的關係, 爬文有看到類似的 12/10 23:45
7F:→ yuffy0327:但試了很久試不出怎麼用, 還麻煩各位為小弟解惑了 12/10 23:45
8F:推 wangpipi:連結資料庫時先下query("SET NAMES utf8")?? 12/11 01:31
9F:→ yuffy0327:回wangpipi: 抱歉忘了補我目前寫的版本, utf8加了之後 12/11 11:54
10F:→ yuffy0327:出現的是utf8的編碼,而不是正常的中文,請問大大有辦法 12/11 11:55
11F:→ DiAdo:用javascript把那些utf8編碼印出來,應該就可以顯示中文了 12/11 12:53
12F:→ MOONRAKER:為什麼非要json_encode() 何不直接print_r()出來看 12/11 15:40