Converting CSV file into an Associative Array in PHP

Today, We want to share with you php read csv file into associative array.In this post we will show you read csv file and convert them into array and process data., hear for how to read single column multiple rows csv file as an array using php we will give you demo and example for implement.In this post, we will learn about Export Json Array To CSV Using Php with an example.

CSV to Associative Array

convert CSV to associative array in PHP

simple PHP code to convert CSV to associative array.

function read_csv($file){
    $products = array();
    $csv_file = $file['folder'] . $file['name'];
    $offilen_csvfile = fopen($csv_file, 'r');
    if(!feof($offilen_csvfile)){
        $i = 0;
        while (!feof($offilen_csvfile)) {
            $product_data[] = fgetcsv($offilen_csvfile, 1000, ",");
            $products[] = array(
                'column1' => !empty($product_data[$i][0])?$product_data[$i][0]:'empty',
                'column2' => !empty($product_data[$i][1])?$product_data[$i][1]:'empty',
                'column3' => !empty($product_data[$i][2])?$product_data[$i][2]:'empty',
                'column4' => !empty($product_data[$i][3])?$product_data[$i][3]:'empty',
                'column5' => !empty($product_data[$i][4])?$product_data[$i][4]:'empty'
            );
            $i++;
        }
    }
    return $products;
}

Calling PHP function
here you can also simple Call the avilable function to Convert CSV file into an associative array in PHP.

$products = read_csv(array('folder'=>'','name'=>'file.csv')); //if your productcsv is in same root folder leave folder empty
var_dump($products);

I hope you get an idea about PHP CSV string to array.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment