How to Read a CSV file to Array in PHP


0

There are several ways to read a CSV file to an array. Online web tools give interfaces to do this. Also, it is simple to create a custom user view for the purpose of reading CSV to the array.

In PHP, it has many native function to read CSV data.

  • fgetcsv() – This reads the CSV file pointer and reads the line in specific to the file handle.
  • str_getcsv() -It reads the input CSV string into an array.

This tutorial gives substitute ways of reading a CSV file to a PHP array. Also, it shows how to develop HTML from the array data of the input CSV.

Quick example

This sample code reads an input CSV file using the PHP fgetcsv() function. This function necessarily the file point to refer to the line to read the CSV row columns.

<?php

// PHP function to read CSV to array
function csvToArray($csv)
{
    // create file handle to read CSV file
    $csvToRead = fopen($csv, 'r');

    // read CSV file using comma as delimiter
    while (! feof($csvToRead)) {
        $csvArray[] = fgetcsv($csvToRead, 1000, ',');
    }

    fclose($csvToRead);
    return $csvArray;
}

// CSV file to read into an Array
$csvFile = 'csv-to-read.csv';
$csvArray = csvToArray($csvFile);

echo '<pre>';
print_r($csvArray);
echo '</pre>';
?>

This code sets the CSV file flow refer to and other parameters to read the data in a loop.

The loop repeat pushes the line data into an array. The PHP array push happen using one of the way.

Save the given comma-separated values to a csv-to-array.csv file. It has to be generated as an input of the above program.

csv-to-array.csv

Lion,7,Wild
Tiger,9,Wild
Dog,4,Domestic

Output:

The above given code returns the following array after reading the input CSV file data.

Array
(
    [0] => Array
        (
            [0] => Lion
            [1] => 7
            [2] => Wild
        )

    [1] => Array
        (
            [0] => Tiger
            [1] => 9
            [2] => Wild
        )

    [2] => Array
        (
            [0] => Dog
            [1] => 4
            [2] => Domestic
        )

)

Map str_getcsv() to read CSV File and change it into a PHP array


This code will be appropriate if you want to skip the step of writing a loop. It saves the developer’s work. But the background development will be the same as the above code.

The PHP file() converts the whole CSV File into an array. Then, the array_map sets the str_getcsv() function as a callback to repeat the array of CSV file rows.

The str_getcsv() imports the CSV row record into an array.

The consequent $csvArray variable will hold the complete CSV record in a multi-dimensional array.

The output of this code will be comparable to that of the quick sample example.

<?php
// a one-line simple option to reade CSV to array
// it uses PHP str_getcsv
$csvArray = array_map('str_getcsv', file('csv-to-read.csv'));
echo '<pre>';
print_r($csvArray);
echo '</pre>';
?>

Convert CSV file to Array and then convert array to HTML

This sample code will be helpful if you want to display the CSV data in the UI in a tabular form.

Mainly, this code must be more helpful since it has the probability of using it in real-time projects. But, the other examples are fundamentals which are also significant to learn about reading CSV file using PHP.

This code repeat the CSV row and reads the column record using fgetcsv() as did in the fast example.

Then, it forms, the HTML table arrangement using the CSV array data. In a past tutorial, we saw code to convert an HTML table into an excel.

<?php

// PHP script to read CSV and convert to HTML table

// create file handle to read CSV file
$csvFile = fopen('csv-to-read.csv', 'r');

if ($csvFile !== FALSE) {
    echo "<table border=1 cellpadding=10>";
    while (($csvArray = fgetcsv($csvFile, 100, ',')) !== FALSE) {
        echo "<tr>";
        for ($i = 0; $i < count($csvArray); $i ++) {
            echo "<td>" . $csvArray[$i] . "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
    fclose($csvFile);
}
?>

Output:

This code will display the HTML table on the screen. The row record is from the input CSV file.


Like it? Share with your friends!

0
Developer

0 Comments