What is csv file in php

How To Read A CSV File & Write Data Into It Using PHP

I’m currently building an email software with PHP to help companies send newsletters to their contact list and I implemented a feature that would enable the software to read & write data into a contact list in CSV format. I will start by explaining what a CSV file is, how to read data & extract data from it, then how to write data into it.

What is a CSV File?

A CSV (Comma Separated Values) File is a text file that uses commas to separate information. Each line of this file is a data record and this means that it can be used to present information in a table-structured format. In the next section, I will show you how to read and extract data from a CSV file.

Reading & Extracting Data From CSV File

I will use the inbuilt function file to read data from the CSV file and then I will use the str_getcsv() to parse the strings containing commas. Before I explain how to use the function str_getcsv() , I want to show you how data from a CSV file is being outputted.

 if($_FILES) var_dump(file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); > ?>   method="post" enctype="multipart/form-data">  type="file" name="file" /> upload    

csv_php_1

When I upload a file using the code above, this is what the output looks like; Now, If you look at the image above you will notice that each of the strings has commas within them and each comma separates one piece of information from the other. I will go ahead and loop through this file again, but this time I will be using the array_map() function and then provide str_getcsv() as the callback that will parse each of these strings that have commas and separate them in a single array.

if($_FILES) //loop through the csv file into an array $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); //dump result var_dump($theCSV); > 

csv_php_2

This is what our array looks like now. You can say that it is much better than the previous output, and we have the column headers (Full Name, Phone, Email) as the first element of this array. Now, let us walk on this array using the array_walk() function and then provide a callback function that will combine the column headers (Full Name, Phone, Email) and each of the CSV data as a new array.

if($_FILES) //loop through the csv file into an array $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/ array_walk($theCSV, function(&$ary) use($theCSV)  $ary = array_combine($theCSV[0], $ary); >); //dump result var_dump($theCSV); > ?> 

csv_php_3

If you noticed, on the callback function above, I used the & operator on the $ary variable to pass it into the function by reference and this makes it possible for us to modify the original array. Visit my article on LinkedIn to learn the difference between passing by reference and passing by value in PHP. When we run the code above, this is what our CSV array now looks like; If you noticed, the first element of this new array still has the headers combined with itself because we had earlier used it to combine with every other element of the CSV array. Now, let us remove the column headers which is the first element of this CSV array using the function array_shift()

if($_FILES) //loop through the csv file into an array $theCSV = array_map('str_getcsv', file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/ array_walk($theCSV, function(&$ary) use($theCSV)  $ary = array_combine($theCSV[0], $ary); >); //remove column headers which is the first element array_shift($theCSV); //dump result var_dump($theCSV); > 

csv_php_4

This is what our final CSV array looks like If you want to extract values from the Email columns only, you can write a loop that will go through the CSV array and then extract data from the email index. We have made it very easy to read and extract data from a CSV file 😃 Now, before we talk about writing data to this same CSV file, I will make the code above a function so that we can return both the column headers and the CSV data as an array because we would need it in the next section 🙂

function readCSV($file) if(empty($file) || !file_exists($file)) return; //store the column headers $headers = null; $theCSV = array_map('str_getcsv', file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); /*Walk through the array and combine the headers which is the first element of our csv array with the rest of the csv data*/ array_walk($theCSV, function(&$ary) use($theCSV, &$headers)  $ary = array_combine($theCSV[0], $ary); //store the headers $headers = $theCSV[0]; >); //remove column headers which is the first element of our csv array array_shift($theCSV); //return data return array( "headers" => $headers, "data" => $theCSV ); > 

Writing Data Into A CSV File

In this section, I will show you an easy way to write data into a CSV file. The logic is to open the CSV file in append mode with fopen() and use fputcsv() to parse the data we want to write to it in CSV format and then it will write this data to the file stream. Now, how do we format and arrange this new data that we want to append to our CSV file? To do that, I will loop through the column headers that are returned from the readCSV() function and then attach the respective values to these headers so that they are able to maintain their position when we append them to the CSV file.

if($_SERVER['REQUEST_METHOD'] == "POST") $file = "./my_csv_file.csv"; //loop through the csv file into an array $csvData = readCSV($file); //create array to store the new data $newData = []; //loop through headers and then add values as a new array foreach($csvData['headers'] as $index => $key) if($key == 'Full Name') $newData[$key] = $_POST['full_name']; >elseif($key == 'Email') $newData[$key] = $_POST['email']; >elseif($key == 'Phone') $newData[$key] = $_POST['phone']; >else $newData[$key] = ''; > > var_dump($newData); > 

csv_php_5

So, this is what the array that will be appended to our CSV file looks like. Before we append this data to the CSV file, we have to get rid of the keys and we can do that easily using array_values()

if($_SERVER['REQUEST_METHOD'] == "POST") $file = "./my_csv_file.csv"; //loop through the csv file into an array $csvData = readCSV($file); //create array to store the new data $newData = []; //loop through headers and then add values as a new array foreach($csvData['headers'] as $index => $key) if($key == 'Full Name') $newData[$key] = $_POST['full_name']; >elseif($key == 'Email') $newData[$key] = $_POST['email']; >elseif($key == 'Phone') $newData[$key] = $_POST['phone']; >else $newData[$key] = ''; > > //open the csv file as in append mode $fp = fopen($file, 'a+'); //remove keys from new data $newData = array_values($newData); //append data to csv file fputcsv($f, $newData); //close the resource fclose($fp); > 

csv_php_5

If you followed the process correctly, you should see a new row of data when you open the CSV file.

CONCLUSION

We have talked about what a CSV file is, how to read and extract data from a CSV file, and then how you can write data back into a CSV file. I explained all the functions and procedures used in this tutorial and I added external links if you want to extend your knowledge. That’s it! Is there anything I’m missing? Do you have any questions for me? I will be in the comments section! 😊

EXTRA

I am open to web development and Technical Writing roles ✅
You will never know if I am a good fit for your company until you give me a chance.

Which validation library do you use for your PHP forms? Have you tried octavalidate, the simplest and easiest validation library with over 4 releases that help to validate your forms using validation rules, sophisticated regular expressions, and PHP’s inbuilt functions? Learn how you can validate your PHP forms using octavalidate Thank you for reading! Photo by Mika Baumeister on Unsplash

Источник

PHP CSV

Summary: in this tutorial, you will learn how to deal with CSV files in PHP, including creating and reading CSV files.

A quick introduction to CSV files

CSV stands for comma-separated values. A CSV file is a text file that stores tabular data in the form of comma-separated values. A CSV file stores each record per line. And it may have a header.

When you open a CSV file using a spreadsheet application, you’ll see that the file is nicely formatted like this:

However, if you view the CSV file in a text editor, it looks like the following:

Symbol,Company,Price GOOG,"Google Inc.",800 AAPL,"Apple Inc.",500 AMZN,"Amazon.com Inc.",250 YHOO,"Yahoo! Inc.",250 FB,"Facebook, Inc.",30Code language: plaintext (plaintext)

Typically, a CSV file uses a comma ( , ) to separate fields in a CSV file. If the field content also contains a comma( , ), the CSV file surrounds that field with double quotes, e.g., “Facebook, Inc..”

Besides using the comma ( , ) character, a CSV file may use other characters to separate fields such as semicolon ( ; ).

Writing to a CSV file

To write a line to a CSV file, you use the fputcsv() function:

fputcsv ( resource $handle , array $fields , string $delimiter = "," , string $enclosure = '"' , string $escape_char = "\\" ) : int|falseCode language: PHP (php)

The following example uses the fputcsv() function to write data to a CSV file:

 $data = [ ['Symbol', 'Company', 'Price'], ['GOOG', 'Google Inc.', '800'], ['AAPL', 'Apple Inc.', '500'], ['AMZN', 'Amazon.com Inc.', '250'], ['YHOO', 'Yahoo! Inc.', '250'], ['FB', 'Facebook, Inc.', '30'], ]; $filename = 'stock.csv'; // open csv file for writing $f = fopen($filename, 'w'); if ($f === false) < die('Error opening the file ' . $filename); > // write each row at a time to a file foreach ($data as $row) < fputcsv($f, $row); >// close the file fclose($f);Code language: HTML, XML (xml)
  • First, define an array that holds the stock data.
  • Second, open the stock.csv file for writing using the fopen() function with the ‘w’ mode.
  • Third, loop through the $data array and write each each element as a line to the CSV file.
  • Finally, close the file using the fclose() function.

Writing Unicode characters

If you’re dealing with Unicode characters especially creating a CSV file for using Microsoft Excel, you need to change the file header using the fputs() function after opening the file as follows:

 $f = fopen($filename, 'w'); if ($f === false) < die('Error opening the file ' . $filename); > fputs($f, (chr(0xEF) . chr(0xBB) . chr(0xBF))); // support unicode // writing to a CSV file //. Code language: HTML, XML (xml)

Reading from a CSV file

To read a CSV file, you use the fgetcsv() function:

fgetcsv ( resource $stream , int $length = 0 , string $separator = "," , string $enclosure = '"' , string $escape = "\\" ) : arrayCode language: PHP (php)

The fgetcsv() function reads a line of CSV data from the file pointer’s position and places it into an array; each line of the CSV file is an array element.

The function fgetcsv() returns false if there is an error occurred while reading the file or when the file pointer reaches the end-of-file.

The following example shows how to read the stock.csv file created above:

 $filename = './stock.csv'; $data = []; // open the file $f = fopen($filename, 'r'); if ($f === false) < die('Cannot open the file ' . $filename); > // read each line in CSV file at a time while (($row = fgetcsv($f)) !== false) < $data[] = $row; >// close the file fclose($f);Code language: HTML, XML (xml)
  • First, open the stock.csv file for reading using the fopen() function.
  • Second, read each line in the file through the file handle and place it into an array. We use the while loop to read the entire CSV file until the file pointer reached the end-of-file.
  • Third, close the file and display the array.

Summary

  • Use the fputcsv() function to write a row to a CSV file.
  • Use the fgetcsv() function to read a row from a CSV file.

Источник

Читайте также:  Разрешить только буквы php
Оцените статью