Friday, November 21, 2025
HomeLanguagesHow to Display Data from CSV file using PHP ?

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:

  • Open XAMPP server and start apache service

  • Open notepad and type the PHP code and save it as code.php

  • Store the CSV file in the same folder. Like xampp/htdocs/gfg/a.csv
  • Go to browser and type http://localhost/gfg/code.php. 

 

Filename: code.php

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:

RELATED ARTICLES

Most Popular

Dominic
32406 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6783 POSTS0 COMMENTS
Nicole Veronica
11929 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11997 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7167 POSTS0 COMMENTS
Thapelo Manthata
6863 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS