2017-05-08 76 views
2

我用笨的框架,連接字符集笨數據爲csv字符編碼問題與阿拉伯

$config['charset'] = 'UTF-8'; 

阿拉伯語在網站和數據庫正確顯示。問題在於將數據導出到csv文件。該文件顯示正確使用上的cPanel代碼編輯器,但是當我下載的文件,並使用Excel中打開它,我得到這個

issue with arabic

當我用記事本打開它阿拉伯語顯示正常,但是當我把文件上傳到facebook產品目錄也沒有正確顯示阿拉伯語。這裏的代碼

$handler = fopen('./directory/'.$fileName,'a+'); 

$exporteddata = 'availability,condition,description'.PHP_EOL; 
for ($x=0; $x<count($cat_products); $x++) { 
     if(strlen(trim($cat_products[$x]->description)) == '0'){ 
     $description = ' '; 
     } 
     else{ 
     $description = $cat_products[$x]->description; 
     } 
     $exporteddata .= 'in stock,new,'.$description.PHP_EOL; 
} 
fwrite($handler,$exporteddata); 
fclose($handler); 

然後重定向到開始下載文件。如果我們忽視了下載功能,只是專注於數據本身,從文件管理器,從網上下載的cPanel我仍然使用這個代碼

public function get_file($file){ 
    header('Content-Encoding: UTF-8'); 
    header('Content-type: text/csv; charset=UTF-8'); 
    header("Content-Type: application/csv"); 
    header('Pragma: no-cache'); 
    header("Content-Disposition: attachment; filename=".basename($file) . "\""); 
    echo "\xEF\xBB\xBF"; 

    $file = 'directory/'.$file; 
    if (!is_file($file)) { 
     header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); 
     echo 'File not found '.$file; 
    } elseif (!is_readable($file)) { 
     header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); 
     echo 'File not readable'; 
    } else { 
     header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK'); 
     readfile($file); 
    } 
} 

功能有問題,所以它不僅僅涉及與寫入功能相關的下載功​​能。

因此,如何解決編碼問題,以便阿拉伯語在csv中正確顯示,如果用excel打開,因此可以使用Facebook正確導入。

[UPDATE] 當我在記事本中打開文件並用ANSI編碼保存時,然後用excel打開新文件,阿拉伯數據顯示正確。我可以使用php將寫入編碼更改爲ANSI嗎?

+0

[如何編寫一個utf-8 CSV,Excel將正確讀取此處解答](http://stackoverflow.com/questions/4348802/how-can-i-output-a-utf-8-csv-in -php-是,Excel的會讀 - 正常)。這是一個老問題,但最近版本的Excel有幾個答案。 – ourmandave

回答

1

這解決了這個問題,但仍然Facebook的錯誤編碼我會聯繫Facebook的。首先

mb_convert_encoding($exporteddata, "Windows-1252", "UTF-8"); 
fwrite($handler,$exporteddata); 
fclose($handler); 

public function get_file($file){ 
    $file = 'directory/'.$file; 
    if (!is_file($file)) { 
     header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); 
     echo 'File not found '.$file; 
    } elseif (!is_readable($file)) { 
     header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); 
     echo 'File not readable'; 
    } else { 
     header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK'); 
     header('Content-Encoding: UTF-8'); 
     header('Content-type: text/csv; charset=UTF-8'); 
     header("Content-Type: application/csv"); 
     header('Pragma: no-cache'); 
     echo "\xEF\xBB\xBF"; 
     header("Content-Disposition: attachment; filename=\"" . basename($file) . "\""); 
     readfile($file); 
    } 
} 

添加回聲 「\ XEF \ XBB \ XBF」;下載功能和mb_convert_encoding保存功能解決了問題,阿拉伯數據在excel和記事本中均正確顯示。