Open In App

How to Display Data from CSV file using PHP ?

We have given the data in CSV file format and the task is to display the CSV file data into the web browser using PHP. To display the data from CSV file to web browser, we will use fgetcsv() function.

Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value file with .csv extension, which allows data to be saved in a tabular format.



fgetcsv() Function: The fgetcsv() function is used to parse a line from an open file, checking for CSV fields.

Execution Steps:



 

Filename: code.php




<!DOCTYPE html>
<html>
  
<body>
    <center>
        <h1>DISPLAY DATA PRESENT IN CSV</h1>
        <h3>Student data</h3>
  
        <?php
        echo "<html><body><center><table>\n\n";
  
        // Open a file
        $file = fopen("a.csv", "r");
  
        // Fetching data from csv file row by row
        while (($data = fgetcsv($file)) !== false) {
  
            // HTML tag for placing in row format
            echo "<tr>";
            foreach ($data as $i) {
                echo "<td>" . htmlspecialchars($i
                    . "</td>";
            }
            echo "</tr> \n";
        }
  
        // Closing the file
        fclose($file);
  
        echo "\n</table></center></body></html>";
        ?>
    </center>
</body>
  
</html>

Output:


Article Tags :