且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中将HTML转换为CSV?

更新时间:2023-01-23 08:44:07

似乎生成的CVS在某些MS excel版本中存在问题. 根据页面:

it seems that produced CVS has problems with some MS excel version. according to this page:

However, certain Microsoft programs (I'm looking at you, Access 97), 
will fail to recognize the CSV properly unless each line ends with \r\n.

所以我将代码修改为:

$td = array();
foreach( $element->find('td') as $row) {
   $td[] = $row->plaintext;
}
fwrite($fp,implode(";",$td)."\r\n");

但也这样说:

Secondly, if the first column heading / value of the CSV file begins with 
`uppercase `ID, certain Microsoft programs (ahem, Excel 2007) will interpret 
the file `as` being in the` SYLK format rather than CSV`

所以我将ID更改为... 总而言之,用小写的'id'和';'作为分隔符,按预期加载 在MS excel 2003中.

So i changed the ID,... to id,... All in all, with lower case 'id' and ';' as delimiter this loaded as expected in MS excel 2003.

已更新:

我找到了一种方法,可以通过添加以下代码将UTF8 .csv正确加载到excel中: 文件中的 BOM 签名. 在PHP中,可以这样做:

i found a way to properly load a UTF8 .csv into excel by adding the BOM signature in the file. In PHP this can be done:

fwrite($fp,"\xEF\xBB\xBF");
...start writing

这3个字符(实际上是1个unicode)forces excel and the likes可以理解 .csv文件作为utf8,因此在内部对其进行解码.

these 3 characters (1 unicode actually) forces excel and the likes to understand the .csv file AS utf8 and therefore decoding it internally.

还有另一种不使用BOM的解决方案,但它是一种黑客行为,而不是 经过良好测试;只需将您的文件创建为 file.txt (请注意,.txt,而不是.csv), 强制excel 询问您所需的编码;您选择utf8并完成.

There is another solution without using the BOM but its a kind of hack and not well tested; just create your file as file.txt (notice the .txt, not .csv), forcing excel to ask you about the encoding you want; you choose utf8 and done.