简体   繁体   English

将HTML表导出到CSV文件

[英]Export HTML table to CSV file

I am making a script which gets a table from your mail and puts it into a CSV file. 我正在编写一个脚本,该脚本从您的邮件中获取一个表格并将其放入CSV文件。

This is the code I use to transfer my html table to CSV 这是我用来将html表转换为CSV的代码

$html = str_get_html($outputstr);   

// For Excel
header('Content-type: application/ms-excel');

// Download File
header('Content-Disposition: attachment; filename=sample.csv');

$fp = fopen("php://output", "w");

// Take out empty lines
foreach($html->find('tr') as $element) {
    $td = array();

    foreach( $element->find('th') as $row) {
        $td [] = $row->plaintext;
    }

    foreach( $element->find('td') as $row) {
        $td [] = $row->plaintext;
    }

    fputcsv($fp, $td);
}

fclose($fp);

The only problem that I'm getting is that when I am opening the CSV file, some of the empty columns have a strange character: 我得到的唯一问题是,当我打开CSV文件时,一些空有一个奇怪的字符:

如

I cannot read through with my PHP script to export it to a database 我无法阅读我的PHP脚本以将其导出到数据库

fgetcsv($handle, 1000, "\t");

How can I fix this problem? 我该如何解决这个问题?

Do I fix this by modifying the code on the part where I create the CSV file or where I read the CSV file when I'm transferring it to a MySQL database? 我可以通过修改将CSV文件传输到MySQL数据库时创建CSV文件或读取CSV文件的部分上的代码来解决此问题吗?

When I use an online html to CSV converter it works fine and I am not facing this issue then. 当我使用在线html到CSV转换器时,它工作正常,然后我没有遇到这个问题。

If there is any code needed then I'd love to share it. 如果需要任何代码,那么我很乐意分享。

Any help would be appreciated. 任何帮助,将不胜感激。

Have you tried setting your charset to UTF-8? 您是否尝试过将字符集设置为UTF-8? Additionally, you're not setting this up as a CSV with your header, instead it is an Excel file. 此外,您没有使用标题将其设置为CSV,而是一个Excel文件。

header("content-type:application/csv;charset=UTF-8");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM