Converting HTML Table to a CSV Automatically Using PHP

Converting HTML Table to a CSV automatically using PHP?

You can use str_get_html http://simplehtmldom.sourceforge.net/

include "simple_html_dom.php";
$table = '<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>';

$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)
{
$th = array();
foreach( $element->find('th') as $row)
{
$th [] = $row->plaintext;
}

$td = array();
foreach( $element->find('td') as $row)
{
$td [] = $row->plaintext;
}
!empty($th) ? fputcsv($fp, $th) : fputcsv($fp, $td);
}

fclose($fp);

Convert HTML to CSV in php?

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.

so i modified the code as:

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

but says also this:

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`

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.

UPDATED:

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

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

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.

How to Export Html Table to CSV and PDF with formatting using Php

Download CSV from HTML from end

$(function () {    $(".export-csv").on('click', function (event) {        // CSV        var filename = $(".export-csv").data("filename")        var args = [$('#fixed_table'), filename + ".csv", 0];        exportTableToCSV.apply(this, args);    });    $(".export-txt").on('click', function (event) {        // txt        var filename = $(".export-txt").data("filename")        var args = [$('#fixed_table'), filename + ".txt", 0];        exportTableToCSV.apply(this, args);    });
function exportTableToCSV($table, filename, type) { var startQuote = type == 0 ? '"' : ''; var $rows = $table.find('tr').not(".no-csv"), // 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/Txt format colDelim = type == 0 ? '","' : '\t', rowDelim = type == 0 ? '"\r\n"' : '\r\n', // Grab text from table into CSV/txt formatted string csv = startQuote + $rows.map(function (i, row) { var $row = $(row), $cols = $row.find('td,th'); return $cols.map(function (j, col) { var $col = $(col), text = $col.text().trim().indexOf("is in cohort") > 0 ? $(this).attr('title') : $col.text().trim(); return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim) .split(tmpRowDelim).join(rowDelim) .split(tmpColDelim).join(colDelim) + startQuote; // Deliberate 'false', see comment below if (false && window.navigator.msSaveBlob) { var blob = new Blob([decodeURIComponent(csv)], { type: 'text/csv;charset=utf8' });
window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) { // HTML5 Blob var blob = new Blob([csv], { type: 'text/csv;charset=utf8' }); var csvUrl = URL.createObjectURL(blob);
$(this) .attr({ 'download': filename, 'href': csvUrl }); } else { // Data URI var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this) .attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); } }
});
<html><head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>Export CSV</title><script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <style type="text/css">        #page-wrapper {             margin: 0 0 0 0;         }    </style></head><body>    <div id="wrapper">        <!-- Page Content -->        <div id="page-wrapper">            <div class="container-fluid">                <div class="row">                    <div class="col-lg-12">                       
<style>

</style><h2> Export to CSV
<!-- Single button --> <span class="btn-group pull-right"> <ul class="dropdown-menu"> <li><a href=javascript:; class="export-csv" data-filename="CSVFILE">CSV</a></li> <li><a href=javascript:; class="export-txt" data-filename="TXTFILE">Flat file</a></li> </ul> </span>
</h2><hr />
<div class="row"> <div class="col-md-2 col-sm-4 col-xs-12">
</div></div><div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table id="fixed_table" class="table table-condensed row-border order-column" cellspacing="0"> <thead> <tr> <th>First Header</th> <th >Second Header</th>

</tr> </thead> <tbody> <tr> <td class="text-center"> First Row column 1</td> <td>First Row column 2</td> </tr> </tbody> </table> </div> </div></div>

</body></html>

Convert a HTML Table to CSV in PHP

If you don't mind using a jquery plugin, you can use something like Datatables and Tabletools. You can see the output here . It's pretty easy and fast to set up

Dynamically display a CSV file as an HTML table on a web page

The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:

<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";

How do I convert an HTML table to csv format?

Here is some perl script. And online converter (java needed). Or you can just manually copy HTML table from browser to OpenOffice Calc / MS Excel and save it as CSV - this will work too.

And here you are step-by-step solution on PHP.



Related Topics



Leave a reply



Submit