I would like to be able to export an HTML table to a csv-file. See code below:
HTML table:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
<script type="text/javascript" src="function.js"> </script>
</head>
<body>
<div class="dataExport">
<button id='export' type="button">Export</button>
</div>
<table class="analysisTable">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Age</th>
<th>Sex</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jane</td>
<td>Doe</td>
<td>19</td>
<td>F</td>
<tr>
<td>John</td>
<td>Doe</td>
<td>41</td>
<td>M</td>
</tbody>
</table>
</body>
</html>
function.js
$( document ).ready(function() {
$("#export").click(function(){
var myTableArray = [];
$("table.analysisTable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() {
arrayOfThisRow.push( $(this).text() );
});
myTableArray.push( arrayOfThisRow );
}
});
$.ajax({
type: "POST",
url: "test_export.php",
data: { data: JSON.stringify(myTableArray) },
cache: false,
response: function(response) {
console.log("Response: " + response);
},
success: function(success) {
console.log("Succes: " + success);
},
error: function(error){
console.log("Error: " + error);
}
});
});
});
export.php
<?php
header('Content-Encoding: UTF-8');
header('Content-Type: application/excel; charset=UTF-8');
header('Content-Disposition: attachment; filename="export.csv"');
$fp = fopen('php://output', 'w') or die ("fopen failed");
$array = json_decode($_POST['data']);
foreach ($array as $row){
$row = array_map("utf8_decode", $row);
//print_r ($row);
fputcsv($fp, $row, ';');
};
fclose($fp);
?>
When clicking the button, this code parses the content of the HTML-table correctly, but prints everything to the console:
Succes: Jane;Doe;19;F
John;Doe;41;M
I've already searched here and on other places, but I can't figure out how to convince the php-script to write create a csv-file instead. Is there something I'm doing wrong here?
EDIT: What I would like to achieve in the end is this: I want to get the data from the HTML-table (I guess by using javascript), use this data in PHP for further processing (database-stuff) and download the final result as a csv-file.