我有一个像这样的html表结构;
<tr style="font-weight: bold">
<td>ID</td>
<td>Navn</td>
<td>Adresse</td>
<td>By</td>
<td>Post nr</td>
<td>E-mail</td>
<td>Telefon</td>
<td>Status og dato</td>
<td>Dropdown info</td>
<td>Produkt info</td>
<td>Buydate</td>
<td>Ref nr. (3 første cifre)</td>
</tr>
<tr>
<td>40563</td>
<td>Firstname Lastname</td>
<td>Address</td>
<td>Copen</td>
<td>2100</td>
<td>ff@hotmail.com</td>
<td>123123</td>
<td>Ikke indløst</td>
<td>EEE-BBB</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
我想通过php将其转换为csv/excel文件.
所以每个都是excel中的一行,每个都是行中的一个单元格,
请问这怎么办?
我研究过并发现使用PHP自动将HTML表转换为CSV?但答案对我来说不正常,我将所有细胞结果都放在一个'细胞'中,所以每行只有一个细胞.
这就是我所尝试过的;
$html = str_get_html($table);
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
foreach($html->find('tr') as $element)
{
$td = array();
foreach( $element->find('td') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
exit;
Run Code Online (Sandbox Code Playgroud)
其中$ table是上面的html.使用简单的html dom插件
小智 4
看来生成的 CVS 与某些 MS Excel 版本存在问题。根据此页面:
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.
Run Code Online (Sandbox Code Playgroud)
所以我将代码修改为:
$td = array();
foreach( $element->find('td') as $row) {
$td[] = $row->plaintext;
}
fwrite($fp,implode(";",$td)."\r\n");
Run Code Online (Sandbox Code Playgroud)
但也这样说:
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`
Run Code Online (Sandbox Code Playgroud)
所以我将 ID,... 更改为 id,... 总而言之,使用小写的 'id' 和 ';' 作为分隔符,它按 MS Excel 2003 中的预期加载。
更新:
我找到了一种通过在文件中添加BOM签名来将 UTF8 .csv 正确加载到 Excel 中的方法 。在 PHP 中可以这样做:
fwrite($fp,"\xEF\xBB\xBF");
...start writing
Run Code Online (Sandbox Code Playgroud)
这 3 个字符(实际上是 1 个 unicode)forces excel and the likes用于将 .csv 文件理解为 utf8,从而在内部对其进行解码。
还有另一种不使用 BOM 的解决方案,但它是一种 hack 并且没有经过充分测试;只需将文件创建为file.txt(注意 .txt,而不是 .csv), 强制 excel询问您想要的编码;你选择utf8就完成了。