Php array csv header

Read CSV Files to Associative Array with Headers PHP Examples

There are 2 ways you can convert CSV to associative arrays in PHP. The modern approach would be to use the array_map, array_filter, & array_combine functions. The older legacy approach uses loops to loop through the content. The first method is preferred in modern applications.

PHP Code to Read a CSV File With Headers into an Associative Array

  1. Open the csv file and get the contents with the array_map function.
  2. Use the array_shift method to get your header row.
  3. Create a PHP array to store your CSV body content.
  4. Loop through the remaining rows with a foreach loop.
  5. Check to make sure the loop content is not empty.
  6. Push a new element to the CSV array that you created using the array_combine function.
  7. Print and test your results.
  8. Continue processing as required.

Have you tried any of the following highly relevant Pluralsight PHP Courses?

Читайте также:  min-width

We love Pluralsight because it has thousands of high-quality course content and is extremely affordable. You don’t have to pay for individual courses. It’s a really small monthly membership and you get access to the entire catalog. You can track and review all of your progress and also obtain additional certifications.

  • PHP Design Patterns
  • PHP: The Big Picture
  • PHP 8: Web Application Security
  • High-Performance PHP
  • Object-Oriented PHP

Learning Paths:

Curious about Pluralsight but not ready to commit? We understand. We were able to get a free trial for you to test-drive and see all of their courses. Click on the link below

CSV PHP Code Examples and Learning Path

Comma-separated files or CSVs are popular for book-keeping and persisting data. Although large-scale applications use cloud storage or databases. However, that doesn’t mean CSVs are out of the league now. We use them often for data entry and maintaining records for simple transactions.

convert csv to associative array PHP

A useful feature of PHP is working with CSV files. We have already seen converting associative arrays to CSV. In this article, we’ll see how to read and convert CSV to associative array PHP. Once you have mapped a CSV file to an associative array, a range of data transformations could be possible. So, let’s jump into the main topic without further ado.

Read CSV files to a PHP associative array

This approach to read CSV files into PHP associative arrays would work in PHP 5 >= 5.3.0, PHP 7, PHP 8. If you’re not using these versions, then perhaps the second option would work for you.

Simplest way to map CSV to associative arrays in PHP

Here’s the simplest way to map CSV to associative arrays in PHP. We have a CSV file with employees data. We need to convert this CSV to associative array PHP.

convert csv to associative array PHP

Let’s look at the code and output and then break down the flow to enhance its understanding.

The PHP script to load the CSV file into the array

Output results of converting CSV to array

Array ( [0] => Array ( [Id] => 1 [Name] => Anna [Age] => 30 [Salary] => 20000 [Department] => Finance ) [1] => Array ( [Id] => 2 [Name] => Adam [Age] => 25 [Salary] => 15000 [Department] => IT ) [2] => Array ( [Id] => 3 [Name] => Bob [Age] => 32 [Salary] => 25000 [Department] => Finance ) [3] => Array ( [Id] => 4 [Name] => Cara [Age] => 20 [Salary] => 12000 [Department] => Logistics ) [4] => Array ( [Id] => 5 [Name] => Daniel [Age] => 28 [Salary] => 27000 [Department] => Engineering ) [5] => Array ( [Id] => 6 [Name] => Franklin [Age] => 25 [Salary] => 20000 [Department] => Quality Assurance ) [6] => Array ( [Id] => 7 [Name] => Gorge [Age] => 21 [Salary] => 15000 [Department] => IT ) [7] => Array ( [Id] => 8 [Name] => Kylie [Age] => 20 [Salary] => 10000 [Department] => Engineering ) [8] => Array ( [Id] => 9 [Name] => Ivan [Age] => 23 [Salary] => 12000 [Department] => Logistics ) [9] => Array ( [Id] => 10 [Name] => James [Age] => 25 [Salary] => 20000 [Department] => Quality Assurance ) ) 

The mapping from CSV to associative arrays in PHP has been done with a few lines of code that we’re going to debunk now.

Break Down

Here’s a flow chart of how the logic flows. We will see how all these functions work together to get the task done.

  1. The array_map function gets a callback function str_getcsv and file function as the second argument.
    • The file function reads the entire CSV file as a string.
    • The array_map function uses the callback function str_getcsv to process the string line by line and convert it into an array.
  2. After step 1, we have an array that has all the comma-separated entities as individual values. We run the array_shift to get the header row.
  3. We iterate over the remaining array values, and by using array_combine, it maps each row to the header.
  4. Finally, the CSV to associative array PHP maps as shown in the output.

The code is rather simple to comprehend if you know these functions. It is recommended to gain familiarity with these functions by following the official PHP documentation page links.

Read and convert CSV to associative array with headers full PHP Example

We’ll see an example here that would also run equally well of PHP version 4 and greater. This example would have more code than the previous one because many latest functions have been replaced with compatible functions, and certain parts of code have been reduced to nested foreach loops to get the task done.

, file('employees.csv')); //Get the first row that is the HEADER row. $header_row = array_shift($rows); //This array holds the final response. $employee_csv = array(); foreach($rows as $row) < if(!empty($row))< $temp = []; //Loop through the individual attributes in the row and map it to a corresponding header. for($i =0; $i < count($row); $i++) < $temp[$header_row[$i]] = $row[$i]; >//Push the row to the employees array. array_push($employee_csv,$temp); > > print_r($employee_csv) ?> 

The output and the flow of the code remain the same. So, we won’t be re-explaining the whole thing. The difference here is that some functions have been replaced with more compatible code. You can try it to figure it out by going through the breakdown in the previous section.

CSV to PHP Associative Arrays with Headers

We have seen how to read and convert CSV to associative arrays in PHP. The first option is the simplest one, but some functions used there are incompatible with PHP versions less than 5. So, the second option deals with incompatibility and uses alternatives to get around the compatibility issue. We hope you’ve learned about converting CSV to associative array PHP.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Источник

PHP массив в файл CSV

PHP массив в файл CSV

Пример как преобразовать массив в CSV и сохранить его диске или отдать на скачивание. Имеем массив $prods :

$prods = array( array( 'id' => '697', 'name' => 'Динамический ортез-стоподержатель', 'category' => 'Ортезы', 'price' => '35990 RUB', ), array( 'id' => '698', 'name' => 'Бандаж на коленный сустав', 'category' => 'Ортезы', 'price' => '3610 RUB', ), array( 'id' => '699', 'name' => 'Бандаж на плечевой сустав', 'category' => 'Ортезы', 'price' => '3700 RUB', ), );
// Подключение к БД. $dbh = new PDO('mysql:dbname=НАЗВАНИЕ_БД;host=localhost', 'ЛОГИН', 'ПАРОЛЬ'); $sth = $dbh->prepare("SELECT * FROM `prods`"); $sth->execute(); $array = $sth->fetch(PDO::FETCH_ASSOC); $prods = array(); foreach($array as $row) < $prods[] = array( 'id' =>$row['id'], 'name' => $row['name'], 'category' => $row['category'], 'price' => $row['price'], ); > 

Отдача файла на скачивание

header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0"); $buffer = fopen('php://output', 'w'); fputs($buffer, chr(0xEF) . chr(0xBB) . chr(0xBF)); foreach($prods as $val) < fputcsv($buffer, $val, ';'); >fclose($buffer); exit();

Сохранение файла на сервере

$buffer = fopen(__DIR__ . '/file.csv', 'w'); fputs($buffer, chr(0xEF) . chr(0xBB) . chr(0xBF)); foreach($prods as $val) < fputcsv($buffer, $val, ';'); >fclose($buffer); exit();

Строка fputs($buffer, chr(0xEF) . chr(0xBB) . chr(0xBF)); добавляет в начало файла метку BOM, благодаря этому файл откроется в Excel с нормальной кодировкой.

Результат

697;"Динамический ортез-стоподержатель";Ортезы;"35990 RUB" 698;"Бандаж на коленный сустав";Ортезы;"3610 RUB" 699;"Бандаж на плечевой сустав";Ортезы;"3700 RUB"

Открытый в Excel

PHP масив в файл CSV

Источник

Оцените статью