1

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);
?>
2
  • 1
    OK? What are you having trouble with? Commented Jul 30, 2009 at 18:36
  • breaking down the rows/cells so i can add formatting tags around them, get the whole thing to display as an html table Commented Jul 30, 2009 at 18:58

1 Answer 1

2

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);
?>
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.