简体   繁体   中英

Saving HTML table to CSV on server from client side

I'm trying to read a.dat file (it's a CSV with delimiter';') and convert it into a table and is done in PHP and is as follows:

<table id='sol'>
<?php
echo "<html><body>";
$f = fopen("/var/www/html/uploads/data_old.dat", "r");
$var = 0;

/* Writes the CSV to table in the page*/
while (($line = fgetcsv($f, 0, ';')) !== false) {
    
    echo "<tr>";
    foreach ($line as $cell) {
        if ($var < 36) {
            echo "<th>" . htmlspecialchars($cell) . "</th>";
            $var = $var + 1;
        }
        else {
            echo "<td><div contenteditable>" . htmlspecialchars($cell) . "</div></td>";
        }
    }
    echo "</tr>";

}

fclose($f);
echo "</body></html>";
?>
</table>

Now after editing the values in the table, I need to save this table on the server. Currently, I can download the table in.dat using a script written in JS as below:

// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ';') {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
            // Escape double-quote with double-double-quote 
            data = data.replace(/"/g, '""');
            // Push escaped string
            row.push('"' + data + '"');
        }
        csv.push(row.join(separator));
    }
    var csv_string = csv.join('\n');
    // Download it
    var filename = 'data_new' + '.dat';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

I'm fairly new to this and any help is highly appreciated.

I might not understand the question here, but I think its something like "I get a csv file from a user - how to display file's fields as an HTML table, and then setup a download link for newly editted file"

If that sounds correct, this is probably what you want. You are correctly displaying the CSV as an HTML table (as far as I can tell).

if htmlspecialchars(..) changes the characters emitted from data_old.dat then we start writing a new CVS file where we'll place the changes emitted by htmlspacechars(..) - and you write in the delimiter yourself by adding ; (as you noted).

$f_ = fopen("/var/www/html/uploads/data_new.dat", "w");

And which ever file we wish the user to download, just place it inside an <a href='...'> tag.

<?php echo "<a href='uploads/data_new.data'>download</a>" ?>

Furthermore (Getting user edits):

While the example above tells us how to setup the backend for the user downloading the file, - it doesn't outline a way for the user to commit edits, and the backend to know about it. To do allow the server to know about user edits, as mentioned in the comments AJAX is the way to go for php.

AJAX is Javascript sending XML (body) notation to the backend as an http request. The way it works is described in the image below. 阿贾克斯

AJAX is accessed by javascript in the browser (hey the where the user is!)

var xhttp = new XMLHttpRequest(); // setup object
// hook function
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // this is ran after we get an OK from the server.
       // after they've committed a change
    }
};
// setup request
xhttp.open("GET", "link/to/your/website", true)
xhttp.send(); // send it

AJAX playground

So far this is pretty vague outlining of what it is, now lets see how we can use it.

So the idea being that when a user changes a field in the table, we run some javascript to send an AJAX request. Specifying what they changed. The server gets the request, updates the changes on the backend, and then sends OK back to the client.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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