Php read csv string

fgetcsv

Данная функция похожа на функцию fgets() , с той разницей, что она производит анализ строки на наличие записей в формате CSV и возвращает найденные поля в качестве массива.

Список параметров

Корректный файловый указатель на файл, успешно открытый при помощи fopen() , popen() или fsockopen() .

Должен быть больше самой длинной строки (в символах), найденной в CSV-файле (включая завершающий символ конца строки). Данный параметр стал необязательным в PHP 5. Если этот аргумент не указан (или равен 0 в версиях PHP 5.1.0 и выше), максимальная длина строки не ограничена, но функция работает немного медленнее.

Необязательный параметр delimiter устанавливает разделитель поля (только один символ).

Необязательный параметр enclosure устанавливает символ ограничителя поля (только один символ).

Необязательный параметр escape устанавливает экранирующий символ (только один символ).

Возвращаемые значения

Возвращает индексированный массив с прочтенными полями.

Замечание:

Пустая строка CSV-файла будет возвращена в качестве массива, содержащего единственный элемент null , ошибки в данном случае не возникнет.

Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.

fgetcsv() возвращает NULL , если передаётся неверный параметр handle или FALSE при других ошибках, в том числе и по достижению конца файла.

Список изменений

Версия Описание
5.3.0 Добавлен параметр escape
5.1.0 Параметр length стал необязательным. По умолчанию равен 0, что означает отсутствие ограничения длины.
4.3.5 fgetcsv() теперь безопасна для обработки бинарных данных

Примеры

Пример #1 Чтение и вывод на экран содержимого CSV-файла

$row = 1 ;
if (( $handle = fopen ( «test.csv» , «r» )) !== FALSE ) while (( $data = fgetcsv ( $handle , 1000 , «,» )) !== FALSE ) $num = count ( $data );
echo »

$num полей в строке $row :

\n» ;
$row ++;
for ( $c = 0 ; $c < $num ; $c ++) echo $data [ $c ] . "
\n» ;
>
>
fclose ( $handle );
>
?>

Примечания

Замечание:

Эта функция принимает во внимание настройки локали. К примеру, если LANG установлена в en_US.UTF-8, то файлы в однобайтовой кодировке будут неправильно прочитаны этой функцией.

Смотрите также

  • str_getcsv() — Выполняет разбор CSV-строки в массив
  • explode() — Разбивает строку с помощью разделителя
  • file() — Читает содержимое файла и помещает его в массив
  • pack() — Упаковывает данные в бинарную строку
  • fputcsv() — Форматирует строку в виде CSV и записывает её в файловый указатель

Источник

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) 

Источник

Читайте также:  Wordpress rest api python
Оцените статью