Search code examples
phpfopen

How to open a CSV-fil with PHP and fopen


Using different snippets of code I've found around the internet, I've put together this code:

HTML:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>

PHP:

<?php
$file = fopen($csv, 'r');
  echo "<table>" ;
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  echo "<tr><td>";
  echo $line[0];
  echo "</td><td>";
  echo $line[2];
  echo "</td><td>";
  echo $line[5] * 1000;
  echo "</td></tr>";


}
fclose($file) . " ";

echo "</table>";

?>

This doesn't work, but if I replace

fopen('MatchResults-12789503873441817.csv'

with

fopen('<name of ulpaded file>.csv'

it works well.

Any suggestions on how to solve this?

Edit: Changed

$file = fopen('csv', 'r');

to

$file = fopen($csv, 'r');

Solution

  • When you use method of post as in

    <form action="upload.php" method="post" enctype="multipart/form-data">
    // -----------------------^^^^^^^^^^^^^
    

    Data will be sent to the PHP script in an array called $_POST

    If the input field is called csv as in

    <input type="text" name="csv" value="" />
    // ----------------^^^^^^^^^^
    

    Then there should be an occurance in $_POST called csv

    $file = fopen($_POST['csv'], 'r');
    

    although you should check that the data was actually sent before using it

    if ( isset($_POST['csv'] ) {
    
        $file = fopen($_POST['csv'], 'r');
    
        // other code
    
    }