簡體   English   中英

寫入 .csv 文件時 PHP 的編碼問題

[英]Encoding issue with PHP while writing in a .csv file

我正在使用一個 php 數組,其中包含從以前的抓取過程(使用Simple HTML DOM Parser )解析的一些值。 我通常可以print / echo顯該數組的值,其中包含特殊字符é,à,è等。但是,問題如下:

當我使用fwrite將值保存在 .csv 文件中時,某些字符未成功保存。 例如, Székesfehérvár很好地顯示在我的HTML php 視圖中,但在我用上面的 php 腳本生成的.csv文件中保存為Székesfehérvár

我已經在 php 腳本中設置了幾項內容:

  • 我正在抓取的頁面似乎是 utf-8 編碼的
  • 我的 PHP 腳本也在標題中聲明為 utf-8
  • 我在代碼的不同地方嘗試了很多iconvmb_encode方法
  • 請注意,當我使用 json_encode 制作 php 數組的 JS console.log 時,字符也會損壞,可能鏈接到我正在抓取的頁面的原始編碼?

這是腳本的一部分,它是在.csv文件中寫入值的部分

<?php 

$data = array(
            array("item1", "item2"), 
            array("item1", "item2"),
            array("item1", "item2"),
            array("item1", "item2")
            // ...
);

//filename
$filename = 'myFileName.csv';

foreach($data as $line) {
    $string_txt = ""; //declares the content of the .csv as a string
    foreach($line as $item) {
        //writes a new line of the .csv
        $line_txt = "";
        //each line of the .csv equals to the values of the php subarray, tab separated
        $line_txt .= $item . "\t";
    }

    //PHP endline constant, indicates the next line of the .csv
    $line_txt .= PHP_EOL;
    
    //add the line to the string which is the global content of the .csv
    $line_txt .= $string_txt;
}

//writing the string in a .csv file 
$file = fopen($filename, 'w+');
fwrite($file, $string_txt);
fclose($file);

我目前卡住了,因為我無法正確保存帶有重音字符的值。

將此行放在您的代碼中

header('Content-Type: text/html; charset=UTF-8');

希望這對你有幫助!

嘗試一下


$file = fopen('myFileName.csv','w');
$data= array_map("utf8_decode", $data);
fputcsv($file,$data);

Excel 在顯示 utf8 編碼的 csv 文件時出現問題。 我以前看過這個。 但是你可以試試utf8 BOM。 我試過了,對我有用。 這只是在 utf8 字符串的開頭添加這些字節:

$line_txt .= chr(239) . chr(187) . chr(191) . $item . "\t";

有關詳細信息: 在 PHP 中使用 BOM 將字符串編碼為 UTF-8

或者,您可以使用 Excel 中的文件導入功能並確保文件來源顯示65001 : Unicode(UTF8) 它應該正確顯示您的文本,您需要將其保存為 Excel 文件以保留格式。

解決方案(由@misorude 提供):

當從網頁HTML內容,有什么顯示在您的調試和什么在腳本真的刮出之間的差異。 我不得不使用html_entity_decode讓PHP解釋HTML代碼中,我真正價值,而不是瀏覽器的解釋。

要在將值存儲在某處之前驗證它們的良好檢索,您可以嘗試在 JS 中使用 console.log 來查看值是否正確驅動:

PHP

//decoding numeric HTML entities who represents "Sóstói Stadion"
$b = html_entity_decode("S&#243;st&#243;i Stadion"); 

Javascript (測試):

<script>
var b = <?php echo json_encode($b) ;?>;

//print "Sóstói Stadion" correctly
console.log(b); 
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM