I’m fairly new to PHP and learning a few basic things. One thing I’m working on is displaying data from a CSV file in a HTML table using PHP. I have it working to an extent, but I cant get rid of the quote mark from the last field in each row.
To start with, it filled in the table, but each field still had it’s quote marks on either side, so I added trims to remove them. That worked except for the last field of each row, which still has a quote mark on the end.
Where am I going wrong?
You may notice I have a trim for each of the 4 entries in the array. Is there a smarter way to do that for the whole array in one go?
<html>
<head>
<title>Reading Data from a CSV file</title>
</head>
<body>
<h1>Table of things from the CSV file</h1>
<table border=1>
<?php
// Open CSV file
$f = fopen("csvdir/testdata.csv", "r");
// Get an array of headers from first line
$arrT = explode("," , fgets($f));
// Remove Quotes
$arrT[0] = trim($arrT[0], "\\"") ;
$arrT[1] = trim($arrT[1], "\\"") ;
$arrT[2] = trim($arrT[2], "\\"") ;
$arrT[3] = trim($arrT[3], "\\"") ;
// Create table header row
echo "<tr><th>" . $arrT[0] . "</th><th>" . $arrT[1] . "</th><th>" . $arrT[2] . "</th><th>" . $arrT[3] . "</th></tr>" ;
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
$arrM = explode("," , fgets($f));
// Remove Quotes
$arrM[0] = trim($arrM[0], "\\"") ;
$arrM[1] = trim($arrM[1], "\\"") ;
$arrM[2] = trim($arrM[2], "\\"") ;
$arrM[3] = trim($arrM[3], "\\"") ;
// Create table rows with data
echo "<tr><td><a href=\\"mailto:" . $arrM[0] . "\\">" . $arrM[0] . "</a></td><td>" . $arrM[1] . "</td><td>" . $arrM[2] . "</td><td>" . $arrM[3] . "</td></tr>" ;
}
fclose($f);
?>
</table>
</body>
</html>