0

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.

3
  • You can not save to the server, but you could upload via AJAX Request. Commented May 4, 2021 at 16:19
  • @MarkusZeller Thank you for the comment. Currently, I'm using the script above to download and then upload it to the server by HTML (form tag with action calling a PHP and method post) and PHP (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)). Is it possible with AJAX Request to avoid this extra step of downloading and uploading? Commented May 4, 2021 at 16:37
  • Are you trying to allow the user to download the CSV file they just uploaded, or do you change values in the CSV and then want to let them download the new copy? Trying to figure out what you're trying to accomplish exactly. Commented May 4, 2021 at 16:40

1 Answer 1

1

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

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the comment. Actually, the user uploads a .dat, then it'll be displayed in a table, the user can edit the values in it and then he needs to download it. But, there is a python script used to find the changes made by the user and inserts a time stamp. So, what I'm currently doing is downloading the edited table where the time is not updated and upload it to the server and the python script is called from PHP.
What I wanted is, to remove the step of downloading the edited table (time not updated) and uploading it for time update. So, in a single go the edited table is to be saved on the server and used by the python script to update the time.
@Ramsey I editted the post to hopefully specify how the AJAX outlines in this aswell. Let me know if you have further questions.
Thanks a lot for the detailed explanation. I'll try to implement it with the resources you gave and I'll surely ping you if I come across any doubts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.