Php read csv file to array

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.

 fclose($csvToRead); return $csvArray; > // CSV file to read into an Array $csvFile = 'csv-to-read.csv'; $csvArray = csvToArray($csvFile); echo '
'; print_r($csvArray); echo '

'; ?>

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.

Lion,7,Wild Tiger,9,Wild Dog,4,Domestic 

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.

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.

"; while (($csvArray = fgetcsv($csvFile, 100, ',')) !== FALSE) < echo ""; for ($i = 0; $i < count($csvArray); $i ++) < echo "" . $csvArray[$i] . ""; > echo ""; > echo ""; fclose($csvFile); > ?> 

This program will display the HTML table on the screen. The row data is from the input CSV file.

csv to html

Download

Leave a Reply Cancel reply

  • PHP
    • Learn PHP
    • PHP Introduction
    • PHP Basics
    • PHP Shopping Cart
    • Payment Gateway
    • Contact Form
    • PHP Login Registration
    • Comments System
    • Types, Variables & Operators
    • PHP Strings
    • PHP Arrays
    • PHP Functions
    • PHP OOPS
    • Event Management System
    • PHP Mail
    • PHP Forms
    • Advanced
    • PHP AJAX
    • RESTful API
    • PHP Databases
    • PHP Sessions and Cookies
    • Error and Exception Handling
    • File Upload
    • File Import Export
    • Files and Directories
    • PHP Date Time
    • PHP XML
    • PHP CSV
      • PHP CSV File Read
      • PHP CSV File Export
      • PHP CSV File Export Using fputcsv()
      • How to Handle CSV with PHP: Read Write, Import Export with Database
      • How to Read a CSV to Array in PHP
      • Convert PHP JSON to CSV
      • Convert PHP Array to CSV
      • Import CSV to Mysql using PHP File Read
      • How to Batch Import Huge CSV Fast using PHP (Million Records in Seconds)

      I’m currently available for freelance work.

      1. Simple PHP Shopping Cart
      2. Stripe Payment Gateway Integration using PHP
      3. User Registration in PHP with Login: Form with MySQL and Code Download
      4. PHP Contact Form
      5. How to Create Dynamic Stacked Bar, Doughnut and Pie charts in PHP with Chart.js

      “ She replied promptly. She asked all the right questions and provided a very quick turnaround time, along with support to get any issues ironed out . ”

      Источник

      Read a CSV to an Array in PHP

      Neema Muganga

      Neema Muganga Last updated Dec 30, 2021

      In this post, I’ll show you how to use PHP’s built-in functions to read and print the contents of a CSV file and convert it into an array. We’ll use fopen() and fgetcsv() to read the contents of a CSV file, and then we’ll convert it into an array using the array_map() and str_getcsv() functions.

      Introduction

      Storing data files in comma-separated values (CSV) format is no new thing. In fact, it’s one of the most common ways of storing data due to its simplicity—CSV files are easy to read and write, and can be opened in a basic text editor. This type of file stores tabular data in the form of plain text.

      An example of such a file would look like this:

      This data represents information about three people, with columns corresponding to their names, age, and job. Although it’s a simple data format, it can be tricky to read and consume.

      Therefore, in this article, I will teach you how to open CSV files using PHP’s native functions like fopen() , how to read the contents of this file with the use of the fgetcsv() method, and lastly how to convert this CSV file into an array using the array_map() function.

      Of course, there are a number of third-party packages we could use to achieve this, but PHP has built-in native functions that work great.

      Prerequisites

      To proceed with this article, you’ll need the following:

      • PHP version 5.6 or above installed on your machine
      • a development environment for PHP—either XAMPP or WampServer work well
      • some basic understanding of PHP concepts

      Displaying a CSV File as a Table

      In this section of the article, we will be reading a simple CSV file that contains a few words separated by the comma delimiter. For a start, we will use the simple file we used above, and then later we can proceed to using a random larger file. Of course, you can create your own file using Microsoft Excel or a text editor and save it with the CSV extension.

      To read the file, we first have to find it in the folder or location it is saved in. For easier access, you may want to save it in the same folder where you have your program file. Then we can use the fopen() function to read the file.

      Afterward, the fgetcsv() function checks for CSV fields from a parsed line of the open file. This function requires three parameters: the file handle returned from fopen() , the maximum length of the line to be read, and the special separator character—which we refer to as the «delimiter». This can be a comma, a semi-colon, or any other separator.

      Create a file named csvtable.php somewhere it can be served with WAMP or XAMPP, and copy the following code.

      $file_to_read = fopen('data.csv', 'r'); 
      while(($data = fgetcsv($file_to_read, 100, ',')) !== FALSE) 

      In this file, we’re first opening the data.csv file, which should contain some comma-separated data. fopen will look for this file in the same folder as csvtable.php. The ‘r’ parameter tells fopen to open the file as read-only.

      If the file is opened successfully, fopen will return a file handle which can be used for other file reading operations. Otherwise, it will return FALSE . Therefore, we check that the file handle is not FALSE before continuing to read the file.

      The fgetcsv() file then fetches CSV fields from the opened file, one line at a time. We tell fgetcsv to read at most 100 characters per line, and to use the comma separator as its delimiter. The words found in the file are then looped through and printed into an HTML table.

      The last function is the fclose() function, which closes the opened file. This releases the memory used by the open file and allows other processes to have access to the file.

      Open csvtable.php through the WAMP or XAMPP localhost server, or run php read.php from the command line to see the following output:

      output of read.php file

      The first part of what we needed to achieve is done already!

      Now, we’ll jump into converting the raw CSV fields into an array.

      Converting the Raw CSV File Into an Array

      Now, there’s more than one way to produce the array. We can use the fgetcsv() function to automatically convert the contents of the CSV file into an array, or we can use array_map .

      Using fgetcsv() to Convert a CSV File Into an Array

      This is similar to the example above, where we used fgetcsv() to render a CSV file as an HTML table. Let’s see this in action. Create a PHP file with the following contents:

      function csvToArray($csvFile) 

      Источник

      Читайте также:  Pre class in html
Оцените статью