note 85385 deleted from function.fgetcsv by danbrown

From: Date: Sun, 17 May 2009 18:07:25 +0000
Subject: note 85385 deleted from function.fgetcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155063@lists.php.net to get a copy of this message
Note Submitter: hunzinker at gmail dot com ---- Here is another function that splits the rows of a CSV file and uses a comma as its delimiter. The function also ignores commas inside of double quotations and removes any double quotes and ultimately prints out the data into a table. If you need to keep the double quotes you'll need to edit the code. The function takes an array as an argument. The array I pass into the function contains the display name and CSV file name. Enjoy! <?php /** * Function to print out data from an uploaded CSV file into a table. * * @param array $data * @return */ function printCSV ($data) { if (is_array($data)) { // open the csv file and read it $dataFile = 'documents/courses/' . $data['course_file']; // change per setup - $data['course_file'] = CSV file name $open = fopen($dataFile, 'r'); $csv = fread($open, filesize($dataFile)); print "<h2>" . $data['name'] . "</h2>"; // optional // split up the rows $csv = preg_split('/[\r\n]/', $csv); $csvData = array(); $i = 0; foreach ($csv as $line) { // splits lines with a comma but ignores a comma wrapped with double quotes $csvData[$i] = preg_split('/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/', $line); $i++; } print "<table width='60%' cellpadding='0' cellspacing='0' class='course-table'>"; for ($j = 0; $j < count($csvData); $j++) { // print the first line with <th> tags if ($csvData && $j == 0) { print "<tr>"; for ($k = 0; $k < count($csvData[$j]); $k++) { // remove the double quotes if (preg_match('/\"/', $csvData[$j][$k])) { print "<th>" . trim($csvData[$j][$k], '"') . "</th>"; // edit if you wish to keep the double quotes } else { print "<th>" . $csvData[$j][$k] . "</th>"; } } print "</tr>"; // print the rest with <td> tags } else { print "<tr>"; for ($k = 0; $k < count($csvData[$j]); $k++) { // remove the double quotes if (preg_match('/\"/', $csvData[$j][$k])) { print "<td>" . trim($csvData[$j][$k], '"') . "</td>"; // edit if you wish to keep the double quotes } else { print "<td>" . $csvData[$j][$k] . "</td>"; } } print "</tr>"; } } print "</table>"; } else { return false; } } ?>

« previous php.notes (#155063) next »