Converting HTML Table to a CSV automatically using PHP?

后端 未结 8 1745
一整个雨季
一整个雨季 2020-12-02 19:20

I am just in need to convert a this html table automatically in csv using PHP. Can someone provide any idea how to do this? Thanks.

$table = \'
8条回答
  •  渐次进展
    2020-12-02 19:56

    You can use this function in separate js file:

    function exportTableToCSV($table, filename) {
    
            var $rows = $table.find('tr:has(td)'),
    
                // Temporary delimiter characters unlikely to be typed by keyboard
                // This is to avoid accidentally splitting the actual contents
                tmpColDelim = String.fromCharCode(11), // vertical tab character
                tmpRowDelim = String.fromCharCode(0), // null character
    
                // actual delimiter characters for CSV format
                colDelim = '","',
                rowDelim = '"\r\n"',
    
                // Grab text from table into CSV formatted string
                csv = '"' + $rows.map(function (i, row) {
                    var $row = $(row),
                        $cols = $row.find('td');
    
                    return $cols.map(function (j, col) {
                        var $col = $(col),
                            text = $col.text();
    
                        return text.replace('"', '""'); // escape double quotes
    
                    }).get().join(tmpColDelim);
    
                }).get().join(tmpRowDelim)
                    .split(tmpRowDelim).join(rowDelim)
                    .split(tmpColDelim).join(colDelim) + '"',
    
                // Data URI
                csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
    
            $(this)
                .attr({
                'download': filename,
                    'href': csvData,
                    'target': '_blank'
            });
        }
    

    Now, to initiate this function, you can use:

    $('.getfile').click(
                function() { 
        exportTableToCSV.apply(this, [$('#thetable'), 'filename.csv']);
                 });
    

    where 'getfile' should be the class assigned to button, where you want to add call to action. (On clicking this button, the download popup will appear) and "thetable" should be the ID assigned to table you want to download.

    You can also change to the custom file name to download in code.

提交回复
热议问题