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>";
Create dynamic webpage based on data from external CSV
UPDATE 25/02/2018
Here is a simple snippet that should get you going.
I really closed all ends and put a comment before almost each line of code so that you can learn from it.
My working assumption is that your CSV looks something like as follows:
Apple, 175.5
IBM, 155.4
MGTI, 2.24
Otherwise, you'll need to update the code accordingly.
I assume you'd like to achieve something a bit more sophisticated, but I just gave you the bare minumum to display what you asked for in your question. I hope this helps you understand and get to your final destination.
// Change to your URL (Must have Access-Control-Allow-Origin header to allow CORS)var csvUrl = 'https://gist.githubusercontent.com/zbone3/96de8a3a836a8d93e7e9f3c3b34667b0/raw/6fdd7a6708cc07bda7fd052fe6f706ad7ac632f4/sample_csv.csv';
function handleCSVResult(csvString) { // Get the div element to append the data to var dataArea = document.querySelector('#csv_data'); // Split csv to rows var rows = csvString.split('\n'); var htmlStr = ''; // Iterate over each row for (var i = 0; i < rows.length; i++) { var row = rows[i]; // split row to cells var cells = row.split(','); // Extract data from cell 1 and 2 of current row var companyName = cells[0]; var stockPrice = cells[1]; // Add extracted CSV data to string htmlStr += '<p>Quote for ' + companyName + ': ' + stockPrice + '</p><br>'; } // Set the string generated from CSV as HTML of the dedicated div dataArea.innerHTML = htmlStr;}
// Init Ajax Objectvar ajax = new XMLHttpRequest();
// Set a GET request to the URL which points to your CSV fileajax.open('GET', csvUrl);
// Set the action that will take place once the browser receives your CSVajax.onreadystatechange = function() { if (ajax.readyState === XMLHttpRequest.DONE && ajax.status === 200) { // Request was successful var csvData = ajax.responseText;
// Do something with that data here handleCSVResult(csvData); }}
// Send requestajax.send();
<div id="csv_data">
<div>
Dynamically add values from a csv in an html table using javascript/jquery
Without knowing the size of the dataset you're working with, I suggest you first iterate through all the CSV dataset in order to populate a list of products with the correct values, and then iterate again on that to populate your HTML table:
function datasetToMap(data) {
var ret = {};
//Initialize a map with all the product rows
$(data).each(function(index, row) {
if(row[0].startsWith("Product")) {
ret[row[1]] = row; //Using the SKU as the key to the map
}
});
//Apply your mixed sets rules to the elements in the ret array
$(data).each(function(index, row) {
if(row[1] === "MIX1") {
ret["PRD1"][2] += 100;
ret["PRD2"][2] += 100;
}
//Do the same for Mixed sets 2 and 3
});
return ret;
}
function appendMapToTable(map) {
var $table = $('#my-table');
Object.keys(map).forEach(function(key, i) {
var rowData = map[key];
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [j] + '">'+cellData+'</td>'));
});
$table.append(row);
});
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
appendMapToTable(datasetToMap(Papa.parse(data).data));
}
});
Note that this expects a table with id my-table
to be already present in your HTML: you could manually parse the first row of your CSV data to add the table headings.
Also note that if your CSV dataset is very big this is definitely not an optimal solution, since it requires iterating through all its lines twice and then iterating again through all the list built with computed values.
Dynamic HTML table from CSV file
Here this code works correctly. Open a file.csv as you described. When you add or delete line in the CSV it works accordingly in the HTML page.
var init;
const logFileText = async file => {
const response = await fetch(file);
const text = await response.text();
all = text.split('\n');
if (init !== all.length) {
//console.log(all.length, init);
init = all.length;
//console.log('changed');
var arr=[];
all.forEach(el => {
el=el.split(',');
arr.push(el);
});
// console.log(arr);
createTable(arr);
}
}
function createTable(array) {
var content = "";
array.forEach(function (row) {
content += "<tr>";
row.forEach(function (cell) {
content += "<td>" + cell + "</td>";
});
content += "</tr>";
});
document.getElementById("t1").innerHTML = content;
}
var file = 'file.csv';
logFileText(file);
setInterval(async () => {
await logFileText(file);
}, 2000);
<table id="t1"> </table>
read csv file from a location and display as html table
Three step process
You need three steps :
1) Use Ajax to fetch data from your server and turn it into an array. You could do this eg. with the following jQuery :
$.ajax({
type: "GET",
url: "data.csv",
success: CSVToHTMLTable
});
2) Once you have get your CSV file, you need to parse it. An easy & reliable way to do it, would be to use a library like Papa Parse :
var data = Papa.parse(data).data;
3) You need to define a function to transform your array into an HTML table. Here's how you could do this with jQuery :
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
Putting everything together
Here's how you can put everything together :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "http://localhost/test/data.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
CSV File to Separate HTML Tables Based on Column Values
This should work :
<?php
$csv = "League,Team,Date,Opponent,Result\namerican,MIN,May 3,UTA,W\namerican,MIN,May 4,SEA,L\namerican,SAC,May 3,DAL,L\namerican,SAC,May 4,TOR,W\nnational,NYN,May 5,BAL,L\nnational,NYN,May 7,MIA,W\nnational,DET,May 6,DEN,L\nnational,DET,May 7,POR,L";
$csv_array = explode("\n", $csv);
$tables = [];
foreach($csv_array as $key => $value) {
if ($key == 0) {
continue;
}
$line = explode(',', $value);
if (array_key_exists($line[1], $tables)) {
$tables[$line[1]][] = $line;
} else {
$tables[$line[1]] = [$line];
}
}
foreach ($tables as $key => $value) {
echo '<h1> ' .$key. ' </h1>'; // YOUR TITLE (Team)
echo "<table>";
echo '<tr>';
foreach (explode(',', $csv_array[0]) as $keyHeader => $valueHeader) {
if (in_array($keyHeader, [0, 1])) {
continue;
}
echo "<th>$valueHeader</th>";
}
echo '</tr>';
foreach ($value as $keyRow => $valueRow) {
echo '<tr>';
foreach ($valueRow as $keyValue => $valueValue) {
if (in_array($keyValue, [0, 1])) {
continue;
}
echo "<td>$valueValue</td>";
}
echo '</tr>';
}
echo '</table>';
}
Here is what i get :
Jsfiddle
Dynamic defualt filter for a HTML table with pure Javascript
const myFunction = () => {
const trs = document.querySelectorAll('Table tr')
const filter = document.querySelector('#myInput').value
const regex = new RegExp(filter, 'i')
const isFoundInTds = td => regex.test(td.innerHTML);
const now = new Date();
const isRightDate = childrenArr => childrenArr.some(td => {
const tdDate = new Date(td.innerHTML);
return tdDate.getDate() === now.getDate()
&& tdDate.getMonth() === now.getMonth();
});
const isFound = childrenArr => childrenArr.some(isFoundInTds)
const setTrStyleDisplay = ({ style, children }) => {
style.display = isRightDate([...children])
&& isFound([
...children // <-- All columns
]) ? '' : 'none';
}
trs.forEach(setTrStyleDisplay)
}
myFunction();
body {
padding: 20px;
}
input {
margin-bottom: 5px;
padding: 2px 3px;
width: 209px;
}
td {
padding: 4px;
border: 1px #CCC solid;
width: 100px;
}
<input
type="text"
id="myInput"
onkeyup="myFunction()"
placeholder="Search for names or countries.."
title="Type in a name or a country">
<table>
<tr>
<td> 12/13/19</td>
<td> 01:39 </td>
<td> Rens: Wat </td>
<td> </td>
</tr>
<tr>
<td> 12/14/20</td>
<td> 01:40 </td>
<td> Rocco Haagenhuizen: In de chat </td>
<td> </td>
</tr>
<tr>
<td> 12/13/21</td>
<td> 01:40 </td>
<td> Rens: Wacht </td>
<td> </td>
</tr>
<tr>
<td> 2/13/21</td>
<td> 01:40 </td>
<td> Rocco Haagenhuizen: Ga naar je chats </td>
<td> </td>
</tr>
</table>
Related Topics
Dompdf Not Rendering Images from the Server But Is Rendering from External Source
Php Fatal Error: Uncaught Pdoexception: Could Not Find Driver
How to Set Current Date as Default Value of an Input
I Have Three Columns, I Want to Combine Them All in One Main_Table
Add Space After Every 4Th Character
Laravel: Products,Categories and Subcategories! (Relation Ships)
Remove License Check from Script Code in Codeigniter
Checking Dates If Between Range of Dates in Laravel 5
Laravel Eloquent How to Get the Minimum Value That Is Not Null
How to Pass an Array Within a Query String
Loop Row in Bootstrap Every 3 Columns
Laravel Unique Validation on Multiple Columns
Telegram Bot Api: How to Send a Photo Using PHP
Multiple Column With Same Search String in Laravel
Laravel - Page Not Found Even That the Route Exists