简体   繁体   中英

Read .CSV file in PHP as a table

I am currently on a project where I need some information to be posted to a csv file and then read back so the previous information can be seen and then edited by the user. Kind of like a database table where the information will be in the cell it should be with some text next to that in another row.

At the minute my code has two tables, one showing the information from the csv and one which sends the data to the csv, but I want this to be merged so that they can see what the previously created information was and then they can edit this information click submit and that is the information which will the appear in the table.

Here is my code at the minute...

$myfile = "outputfile.csv"; 
if (!isset($_POST['submit'])) {
$f = fopen($myfile, 'r');
echo "<table>";
while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
        echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>\n";
}
fclose($f);
echo "\n</table>";
echo "
<form action='' method='POST'>
<table border='1'>
    <tr>
        <td><input name='var1' type='text'></td>
        <td>MMR</td>
    </tr>
    <tr>
        <td><input name='var2' type='text'></td>
        <td>FIVE_IN_ONE</td>
    </tr>
    <tr>
        <td><input name='var3' type='text'></td>
        <td>BOOSTER</td>
    </tr>
    <tr>
        <td><input name='var4' type='text'></td>
        <td>MENC</td>
    </tr>
</table>
<input name='submit' type='submit' value='Submit'>
</form>";
} else {
    $text1 = $_POST['var1'];
    $text2 = $_POST['var2'];
    $text3 = $_POST['var3'];
    $text4 = $_POST['var4'];

    $fh = fopen($myfile, 'w+');
    fwrite($fh, $text1 . "\r\n" . $text2 . "\r\n" . $text3 . "\r\n" . $text4);
    fclose($fh);

    echo $text1 . "<br>" . $text2 . "<br>" . $text3 . "<br>" . $text4; 
}

PHP has csv functionality built in:

$arrayOfValues = str_getcsv(file_get_contents('myfile.csv'));
foreach($arrayOfValues as $row)
{
  foreach($row as $col)
  {
    echo $col . '&nbsp;';
  }
  echo '<br>';
}

As David said, use str_getcsv. To put everything in place so that people can live-edit, you want to display the form like this:

$arrayOfValues = str_getcsv(file_get_contents('myfile.csv'));
foreach($arrayOfValues as $row)
{
  $index=0;
  echo "<tr>";
  foreach($row as $col)
  {
     echo "<td><input name='var".$index."' type='text' value='".$col."'></td>";
     $index++;
  }
  echo "</tr>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM