写入 .csv 文件时 PHP 的编码问题

问题描述 投票:0回答:5

我正在使用一个 php 数组,其中包含从之前的抓取过程中解析的一些值(使用

Simple HTML DOM Parser
)。我通常可以
print
/
echo
这个数组的值,其中包含特殊字符
é,à,è
等。 但是,问题如下:

当我使用

fwrite
将值保存在 .csv 文件中时,某些字符未成功保存。例如,
Székesfehérvár
在我的
HTML
中的php视图上很好地显示,但在我使用上面的php脚本生成的
Székesfehérvár
文件中保存为
.csv

我已经在 php 脚本中设置了几件事:

  • 我正在抓取的页面似乎是utf-8编码的
  • 我的 PHP 脚本也在标头中声明为 utf-8
  • 我在代码的不同地方尝试了很多
    iconv
    mb_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);

我目前陷入困境,因为我无法正确保存带有重音字符的值。

php web-scraping utf-8 character-encoding
5个回答
1
投票

将此行放入您的代码中

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

希望这对您有帮助!


1
投票

尝试一下


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


0
投票

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 文件以保留格式。


0
投票

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

当从网页中抓取 HTML 内容时,调试中“显示”的内容与脚本中真正“抓取”的内容之间存在差异。我必须使用 html_entity_decode 让 PHP 解释我已抓取的 HTML 代码的

true
值,而不是浏览器的解释。 要在将值存储在某处之前验证值的良好检索,您可以尝试在 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>

此功能删除BOM:

0
投票

© www.soinside.com 2019 - 2024. All rights reserved.