tags:

views:

268

answers:

2

Im trying to figure out how to take the data returned by fgetcsv, and format it into a readable/editable table, and then use fputcsv to save that table

so far i have this

<?php
$row = 1;
$handle = fopen("csv.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "\n";
    }
}
fclose($handle);
?>
A: 

The following code will output the CSV in an html table. To make it editable wrap the echo ..$val.. with tags and add a php form handler that takes the result and reforms a CSV

<?php
    $row = 1;
    $handle = fopen("csv.csv", "r");
    echo("<table>");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     echo("<tr>\r\n");
     foreach ($data as $index=>$val) {
      echo("\t<td>$val</td>\r\n");
     }
     echo("</tr>\r\n");
    }
    echo("</table>");
    fclose($handle);
?>
Ben Reisner
As a security measure (if you do not plan on having HTML in the CSV file), it might be interesting to escape the output of $val with something like htmlspecialchars or htmlentities, to avoid injecting any HTML/JS code into the page.
Pascal MARTIN
Is there any way of extracting each column into its own variable so i can say for example, 1-4 colums = text, colum 5 = lists, colum 6-10 = text areas....ect?
Patrick
PascalMARTIN is absolutely correct, otherwise if you CSV contained something like '4<5' then the web browser would get confused.Patrick: The way I would do that would be to have a series of IF statements that branch the echo ..val... into a different case depending on the index variable. That would work if your CSV is always ordered the same way.If you have a header row with column names you could treat the first row as a special case and create a name to index map and then you could branch based upon the column name.
Ben Reisner
A: 

could someone add to this with putting css class's on the tr and td even the th, i would like to stripe the rowass if poss.

rowan