Converting CSV file into an Array in PHP

Posted By : Ishaan Madan | 12-Jan-2017

This Blog helps to illustrate the method to import CSV file into an associative PHP array. PHP uses fgetcsv function for this specific purpose. The array created is associative which helps in accessing the value by the column field heading at the top of the CSV file.

The PHP fgetcsv function imports and reads the CSV file into an associative array on the basis of the column heading in the first row. To use it, we can call the function with an appropriate file as a parameter. The function after execution outputs an associative array containing imported .csv file data.

Note:  Imported CSV must possess first row as column headings as it is used to generate the associative array elements.

Read CSV using PHP

<?php
 
function ImportCSV2Array($filename)
{
    $row = 0;
    $col = 0;
 
    $handle = @fopen($filename, "r");
    if ($handle) 
    {
        while (($row = fgetcsv($handle, 4096)) !== false) 
        {
            if (empty($fields)) 
            {
                $fields = $row;
                continue;
            }
 
            foreach ($row as $k=>$value) 
            {
                $results[$col][$fields[$k]] = $value;
            }
            $col++;
            unset($row);
        }
        if (!feof($handle)) 
        {
            echo "Error: unexpected fgets() failn";
        }
        fclose($handle);
    }
 
    return $results;
}

Example

<?php
 
$filename = "demo.csv";
$csvArray = ImportCSV2Array($filename)
 
foreach ($csvArray as $row)
{
    echo $row['column1'];
    echo $row['column2'];
    echo $row['column3'];
}

Explanation?

The function reads each and every line of the CSV file using fgetcsv function. This function renders the line for fields in CSV format to return an associative array possessing the required data. The array has the first item at 0th location, second at 1st and process continues.

The initial row of data acts like the headings, thereafter a loop iterates over each element of array from fgetcsv and enters it for each column heading.The associative array is useful because it eliminates indexes which otherwise often confuse and are hard to remember for any specific field(column).

Thanks

About Author

Author Image
Ishaan Madan

Ishaan, a skilled technical project manager, excels at breaking down complex projects into manageable tasks. With a background in both technology and project management, he offers a unique perspective to every project he undertakes. His effective communication skills enable him to collaborate seamlessly with both technical and non-technical stakeholders, ensuring everyone is aligned towards shared objectives. He has hands-on experience in utilizing agile methodologies like Scrum and Kanban to drive project management and foster team collaboration. He leverages project management tools such as JIRA, Trello, and Clickup to monitor progress, manage tasks, and facilitate communication among team members and stakeholders. Moreover, his proficiency in full-stack development empowers him to comprehend the technical aspects of projects and provide guidance to developers when necessary. He demonstrates expertise in utilizing popular Python frameworks like Django and Flask, along with data analysis and manipulation libraries such as NumPy and Pandas. On the front-end, Ishaan adeptly employs JavaScript libraries like React and Angular to craft visually appealing and user-friendly interfaces. Additionally, he possesses proficiency in HTML, CSS, and JavaScript for designing responsive and mobile-friendly layouts.

Request for Proposal

Name is required

Comment is required

Sending message..