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

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 | ...

நீங்கள் Digital Marketing வழியாக உங்கள் தொழிலுக்கு அதிக வாடிக்கையாளர்கள் பெற விரும்புகிறீர்களா?இதை கட்டாயம் படியுங்கள்.

நீங்கள் தொழிலதிபரா?  நீங்கள் Digital Marketing வழியாக உங்கள் தொழிலுக்கு அதிக வாடிக்கையாளர்கள் பெற விரும்புகிறீர்களா? இதை கட்டாயம் படியுங்கள்.  தொழில் சிறியதாக இருந்தாலும், பெரியதாக இருந்தாலும் சரி அதன் தொழில் வளர்ச்சியடைய தொழில்நுட்பம் (technology) பெரிதும் உதவுகிறது. தொழில்நுட்பங்கள் தொழிலின் பல மட்டங்களில் பயன்படுகிறது. தயாரிப்பு மற்றும் சேவையை சந்தைப்படுத்த டிஜிட்டல் மார்க்கெட்டிங் (Digital Marketing) தொழில்நுட்பம் பெரிதும் உதவுகிறது. மின்னணு ஊடகங்கள் வழியாக தயாரிப்பு மற்றும் சேவையை சந்தைப்படுத்துதல் Digital Marketing ஆகும். இத்தகைய டிஜிட்டல் மார்க்கெட்டிங்கில் பல உத்திகள் (strategy) மூலம் பொருட்கள் / சேவையை   சந்தைப்படுத்தலாம். ஆன்லைன் வழியாக பல டிஜிட்டல் மார்க்கெட்டிங்கை எவ்வித செலவும் இல்லாமல் செய்துகொள்ளலாம் Location: Social Media Marketing இன்றைய நிலையில் பெரும்பாலோனோர் சமூக வலைத்தளங்களை (Social media) பயன்படுத்துகின்றனர். ஒரு தயாரிப்பு மற்றும் சேவை அவர்களை சென்றடைய சமூக வலைத்தள மார்கெட்டிங்கை பின்பற்றுவது அவசியமாகும். Face book, Twitter, Google plus, ...

How to Run Java Program

  How to Run Java Program Java is a popular, high-level, object-oriented programming language that was developed by James Gosling and his team at Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is widely used for developing various kinds of software, including web applications, desktop applications, mobile applications, games, and more. Step by Step Implementation To run a Java program, you need to follow these steps: Step 1:  Install Java Development Kit (JDK) on your computer. You can download the JDK from the Oracle website or any other reliable source.   Step 2:  Write your Java code in a text editor such as Notepad or any other code editor. Save the file with a .java extension and file type as ‘All files’ in the desired location. Step 3:  Open the command prompt (Windows) or terminal (Mac or Linux). Step 4:  Navigate to the directory where you saved your Java code using the “cd” command. Step 5:  C...