PHP read csv file, save in variable, and display in the browser

In this case, we would like to read comma separated value (csv) than save in the php variable and display to the browser.

For example, we have csv file with name data.csv and containing data looks like below:

"First Name","Last Name","e-mail"
"John","Doe","[email protected]"
"Alex","Joe","[email protected]"

Create a php file for example readcsv.php. The PHP code is looks like below:

<?PHP

    $file_handle = fopen('./data.csv', 'r');
    while (!feof($file_handle) ) {
        $text[] = fgetcsv($file_handle, null, ",");
    }
    fclose($file_handle);


    echo '<pre>';
    print_r($text);
    echo '</pre>';

?>

Open php file in the browser and it will display csv data in the array format.

reference:

  • http://codedevelopr.com/articles/reading-csv-files-into-php-array/
  • http://php.net/manual/en/function.fgetcsv.php

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.