Skip to main content

How to Read a CSV to Array in PHP

 There are many ways to read a CSV file to an array. Online hosted tools provide interfaces to do this. Also, it is very easy to create a custom user interface for the purpose of reading CSV to the array.

In PHP, it has more than one native function to read CSV data.

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

This article provides alternate ways of reading a CSV file to a PHP array. Also, it shows how to prepare HTML from the array data of the input CSV.

Quick example

This example reads an input CSV file using the PHP fgetcsv() function. This function needs 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 program sets the CSV file stream reference and other parameters to read the records in a loop.

The loop iteration pushes the line data into an array. The PHP array push happens using one of the methods we have seen in the linked article.

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

csv-to-array.csv

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

Output:

The above program 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
        )

)

csv to PHP array

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

This program will be suitable if you want to skip the step of writing a loop. It saves the developer’s effort. But the background processing will be the same as the above program.

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

The str_getcsv() imports the CSV row data into an array. In a previous article, we have seen about handling CSV file read and other operations like import, and export.

The resultant $csvArray variable will contain the complete CSV data in a multi-dimensional array.

The output of this program will be similar to that of the quick 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 to Array and then convert array to HTML

This example will be useful if you want to display the CSV content in the UI in a tabular form.

Mostly, this code must be more useful since it has the possibility of using it in real-time projects. But, the other examples are basics which are also important to learn about reading CSV using PHP.

This code iterates the CSV row and reads the column data using fgetcsv() as did in the quick example.

Then, it forms the HTML table structure using the CSV array data. In a previous 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 program will display the HTML table on the screen. The row data is from the input CSV file.

csv to html
Download

Comments

Popular posts from this blog

IOT Projects souce code

IOT  Projects souce code What is IoT? The Internet of Things (IoT) is a network where everyday objects like devices, vehicles, and appliances have sensors and internet connectivity. It lets them gather and share data, work together, and perform tasks without human control. This helps boost automation and efficiency across different areas. You can learn IoT to understand its core components and get further knowledge of its functionalities. 20 IoT Projects with Source Code When it comes to IoT, there are many interesting ideas to explore, from making your home smarter to making an autonomous drone. No matter if you’re just starting or have experience, here are 20 Internet of things projects for beginners and advanced professionals. Simple IoT Project Ideas for Beginners For beginner-level, you can start with simple and fun IoT project ideas that involve basic components like sensors, actuators, and microcontrollers. Below are a few of them: 1. Smart Home Automation Smart home automat...

Connecting R to MySql in English #Training Trains

software design institute training

  ONLINE-OFFLINE IN-PLANT/INTERNSHIP With Certificate Training For B.E(ECE,EEE,CSE,IT,AI,ML,DataScience,Cyper Security),MCA, B.Sc,M.E,M.Tech. @ TrainingTrains.Online Classes Available 100 % Job placement Training Full Stack Developer | Placement Training In-plant Training/Internship Training with Project supports the various Engineering and Non-Engineering, Arts Students to develop their Skills on the IT Companies/Corporate Expectations. DURATION OF IN-PLANT TRAINING: 1 week and Above.DURATION OF INTERNSHIP: 1 Month and Above Internship-inplant training For All Departments students, Internship- inplant Training Python | Java | Full Stack Development | UI & UX | C& C++ | Php | Web Designing - HTML, CSS, Java Script, Bootstrap | MEAN Stack | MERN Stack | MEARNStack | Android | Kotlin | Flutter | Database - Oracle, Mongo DB, MySQL, MS SQL Serer | Visual Studio Code | Objective C | Swift | Go Lang | Frame work - Laravel, Django, Vue JS | Machine Learning | React JS | ...