Drongo_III Posted July 1, 2011 Share Posted July 1, 2011 Hi Guys I'm trying to create a little script that can read in a csv file and then write this as html to a text file. I'm ok reading in the csv and generating the html table in browser but i'm at a loss as to how i can pass this newly create html table into a variable to pass to the filewrite. What i want to acheive is a text file with the html code for the table. echo "<table>\n"; $row = 0; $handle = fopen("testfile.csv", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if ($row == 0) { // this is the first line of the csv file // it usually contains titles of columns $num = count($data); echo "<thead>\n<tr>"; $row++; for ($c=0; $c < $num; $c++) { echo "<th>" . $data[$c] . "</th>"; } echo "</tr>\n</thead>\n\n<tbody>"; } else { // this handles the rest of the lines of the csv file $num = count($data); echo "<tr>"; $row++; for ($c=0; $c < $num; $c++) { echo "<td>" . $data[$c] . "</td>"; } echo "</tr>\n"; } } fclose($handle); echo "</tbody>\n</table>"; Still very new to php so any advice or help would be appreciated. Thanks, Drongo Link to comment https://forums.phpfreaks.com/topic/240873-creating-a-file-with-html-table/ Share on other sites More sharing options...
Drongo_III Posted July 1, 2011 Author Share Posted July 1, 2011 Well solved this noob problem now! For anyone who may, at the start of the php career, be similarly perplexed here is what i did... <?php $builder = "<table>\n"; $row = 0; $handle = fopen("testfile.csv", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if ($row == 0) { // this is the first line of the csv file // it usually contains titles of columns $num = count($data); $builder = $builder . "\n<tr>"; $row++; for ($c=0; $c < $num; $c++) { $builder = $builder . "<td>" . $data[$c] . "</td>"; } $builder = $builder . "</tr>\n\n<tbody>"; } else { // this handles the rest of the lines of the csv file $num = count($data); $builder = $builder . "<tr>"; $row++; for ($c=0; $c < $num; $c++) { $builder = $builder . "<td>" . $data[$c] . "</td>"; } $builder = $builder . "</tr>\n"; } } fclose($handle); $builder = $builder . "</tbody>\n</table>"; echo $builder; $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); fwrite($fh, $builder); fclose($fh); ?> Sorry for posting such a silly question i just couldn't figure it at first :/ Drongo Link to comment https://forums.phpfreaks.com/topic/240873-creating-a-file-with-html-table/#findComment-1237286 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.