Download html content in csv or txt file, how? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Download html content in csv or txt file, how?

I am making a page to search for elements in a database, what I want to do is that when a user enters a page of an element where its information is displayed, they have the option to download the information of the element in a csv file and/or txt. I'm working with HTML, CSS, JavaScript, PHP, and MySQL.

7th Oct 2020, 6:03 AM
Leo Arteaga
2 Answers
+ 2
There are lots of ways to create a downloadable CSV or txt file. You could hyperlink to an API on the server that responds with the file's content. You could suggest a file name like this: header('Content-Disposition: attachment; filename="downloaded.csv"'); Some ways to encode your CSV data are explained at: https://www.codewall.co.uk/write-php-array-to-csv-file/ There are a couple ways to make sure the link is processed as a download instead of the browser trying to render it. 1. If you use an a tag, set the "download" attribute to ensure it actually downloads. 2. Write your PHP to respond with header('Content-Type: application/octet-stream'); That content type is almost guaranteed to trigger a download. If JavaScript has all the exportable data, you could create a data URL that base-64 encodes the content of the file you want to download. This can work without even hitting a PHP script. The following gives more detail: https://www.bitdegree.org/learn/javascript-download Test your CSV export handles edge cases like commas and quotes in your exported data. It is easy to mishandle commas, quotes, and semicolons when exporting CSV because they're such important characters for the format.
7th Oct 2020, 9:00 PM
Josh Greig
Josh Greig - avatar
0
Thank you, I'll try it.
8th Oct 2020, 1:24 AM
Leo Arteaga