2014-07-11 60 views
0

我試圖連接到mysql數據庫並獲得字符串在UTF-8PHP - > mysql錯誤編碼

 <?php 
     $con=mysqli_connect("localhost","root","pass","db"); 
     mysql_set_charset('utf-8'); 
     mysql_query("set names 'utf8'"); 
     mysql_query('set character set utf8'); 

但是下面的代碼進行響應我,這是我從數據庫獲取字符串中ASCII進行編碼。

 $result = mysqli_query($con,"SELECT * FROM tweet"); 
     $content =array(); 
     while($row = mysqli_fetch_array($result)) { 
        $content[] =$row['content']; 
     } 
     echo mb_detect_encoding($content[0]);//this line prints: ASCII 
     mysqli_close($con); 
     ?> 

使用下面的代碼我得到的所有文字土耳其除了'G', 'S', 'I'

$current_encoding = mb_detect_encoding($content[0], 'auto'); 
for($x=0;$x<sizeof($content);$x++){ 
    $content[$x] = iconv($current_encoding, 'UTF-8', $content[$x]);} 
echo mb_detect_encoding($content[0]);//this line again prints: ASCII 

我怎樣才能從數據庫編碼UTF-8字符串?

+0

實際上'mb_detect_encoding'是錯誤的功能在所有使用,它會嘗試猜編碼,所以不要依靠其返回,只需使用utf8編碼將您的內容輸出到HTML並在瀏覽器中打開 - 您將看到一切都是正確的 –

回答

0

由於您使用mysqli_connect連接到數據庫,您需要使用:

mysqli_set_charset($con, 'utf-8'); 

,而不是

mysql_set_charset('utf-8'); 
mysql_query("set names 'utf8'"); 
mysql_query('set character set utf8'); 

只是連接到數據庫之後。因此,您不需要使用任何mb_detect_encoding或iconv函數,因爲假定數據正確插入,您也將得到正確的結果。

你也應該確保,你的表/字段已設置utf8編碼例如utf8_encode_ci