phpcsvfgetcsvfputcsv

writing to CSV using fgetcsv


I am having some trouble with my PHP code. Basically I have a list of people in CSV, and I am reading that file into a table using fgetcsv. What I'm trying to do is have their names appear as a Link, they click on the link, it calls fputcsv, and puts a 1 next to their name.

Currently I only have the displaying portion working. I'm not really sure where to start on the writing part.

Any insight would be greatly appreciated.

Thanks a bunch!!

  <?php
  $row = 1;
  $handle = fopen("test/list.csv", "r");
  echo("<table>");
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      echo("<tr>\r\n");
      foreach ($data as $index=>$val) {
              echo("\t<td><a href=\"#\">$val</a></td>\r\n");
      }
      echo("</tr>\r\n");
  }
  echo("</table>");
  fclose($handle);
  ?>

Solution

  • You can't treat a csv file as a database directly. You'd need to have some means of indicating WHICH line the clicked row came from in the original csv file. Either by line number, or (preferably) some unique ID field in each row.

    I'll pretend that column 0 of the csv file is a unique indentifier for the row, so you'd have this for ouptut:

      foreach ($data as $index=>$val) {
              echo("\t<td><a href=\"update.php?id={$data[0]}\">$val</a></td>\r\n");
      }
    

    And then in the update.php script, in basic pseudo-ish code:

    <?php
    $id = $GET['id'];
    
    $fh = fopen('test/list.csv', 'rb');
    $out = fopen('newlist.csv', 'wb');
    while($row = fgetcsv($fh)) {
       if ($row[0] == $id) {
           $row[xxx] = 1; // write '1' for this row because it's the row that was clicked on
       }
       fputcsv($out, $row); // write out to new file
    }
    

    Note that I'm using a second file for the modified output. this is safer than trying to edit the original csv in-place. Once you've made any necessary changes, you simply move the new file over the old one and your edits are done.