【发布时间】:2019-08-26 10:53:08
【问题描述】:
我正在使用一个 php 数组,其中包含一些从之前的抓取过程中解析的值(使用 Simple HTML DOM Parser)。我可以正常print/echo这个数组的值,其中包含特殊字符é,à,è等BUT,问题如下:
当我使用fwrite 将值保存在 .csv 文件中时,某些字符未成功保存。例如,Székesfehérvár 在HTML 的我的php 视图中很好地显示,但在我使用上面的php 脚本生成的.csv 文件中另存为Székesfehérvár。
我已经在 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);
我目前卡住了,因为我无法正确保存带有重音字符的值。
【问题讨论】:
-
“我正在抓取的页面似乎是 utf-8 编码的” - 更确切地说,您正在抓取的页面实际上使用这些数字实体来表示这些字符已经。您可能只是没有注意到,因为您在浏览器将它们解释为 HTML 之后查看了调试输出。
html_entity_decode应该有帮助。 -
@misorude,感谢您的帮助。我不太明白你的评论,让我补充一点:当我对我的
$data数组执行print_r时,所有字符都是可用的,但问题是当我尝试用这个数组做其他事情时,比如作为 JS 的json_encode,或写入 .csv。你明白我的意思吗 ?谢谢 -
做一个
print_r("Sz&#233;kes");- 注意到什么了吗? -
是的,
print_r返回Székes。跟着你,我使用htmlentities来获取值的 original 数字实体,但我现在的问题是:我如何将值 store 为Székes例如,而不是Sz&#233;kes?谢谢@misorude -
“是的,
print_r返回Székes” - 那么你现在明白我最初的评论了吗? “我如何将值存储为Székes,而不是Sz&#233;kes?” - 通过将你拥有的值变成你想要的值 - 你目前 有Sz&#233;kes。不,我没有说要使用htmlentities。
标签: php web-scraping utf-8 character-encoding