To or from csv excel php

Содержание

  1. Как в PHP делать импорт/экспорт CSV для MS Excel
  2. Описание формата CSV для Excel
  3. Что делает стандартная функция экспорта в CSV в PHP
  4. Что делает стандартная функция импорта в CSV в PHP
  5. Итоговые функции работы с CSV
  6. Как открыть Экселем CSV-файл в кодировке UTF-8
  7. CSV Export/Import with PHPExcel
  8. 3 Answers 3
  9. Linked
  10. Related
  11. Hot Network Questions
  12. Subscribe to RSS
  13. csv to excel conversion
  14. 6 Answers 6
  15. Linked
  16. Related
  17. Hot Network Questions
  18. Subscribe to RSS
  19. How to convert CSV file to Excel in PHP
  20. 1. EasyXLS on Windows using .NET Framework (COM+) with PHP
  21. 2. EasyXLS on Linux, Mac, Windows using Java with PHP
  22. EasyXLS on Windows using .NET Framework (COM+) with PHP
  23. Step 1: Download and install EasyXLS Excel Library for COM+
  24. Step 2: Verify if COM and .NET extension is enabled in PHP
  25. See also
  26. How to enable COM and .NET extension in PHP?
  27. Step 3: Verify if EasyXLS is registered
  28. See also
  29. How to verify if EasyXLS is registered?
  30. Step 4: Run PHP code that converts CSV file to Excel
  31. EasyXLS on Linux, Mac, Windows using Java with PHP
  32. Step 1: Download EasyXLS Excel Library for Java
  33. Step 2: Install PHP/Java Bridge
  34. Step 3: Setup EasyXLS library in Tomcat
  35. Step 4: Run PHP code that converts CSV file to Excel
  36. How to handle CSV files with PHP
  37. How to convert Excel files to CSV files
  38. How to handle CSV file with PHP
  39. How to convert a CSV file into a PHP multidimensional array
  40. Conclusion

Как в PHP делать импорт/экспорт CSV для MS Excel

Многие, работая с PHP и MySQL, сталкивались с проблемой экспорта/импорта данных в CSV файл, понятный для Excel. Функции fputcsv() и fgetcsv() работают не так, как нам хотелось бы. И открывая полученный CSV-файл в Экселе мы видим половину строки в одной ячейке, а другую часть строки во второй. Иногда такие ошибки интерпретации данных Экселем связаны с его ограничением количества данных в одной ячейке – 50 000 символов, если больше, то оставшиеся данные отображаются в новой строке.

Описание формата CSV для Excel

Программа Microsoft Excel понимает CSV-файлы как разделенные ячейки, разделенные символом точка с запятой (;), а строка заканчивается символом перевода строки. Если же в самой ячейке содержатся символы точка с запятой (;) либо перехода на новую строку, то такая ячейка обрамляется символом кавычек («).

Например:
ячейка1; «ячейка2 с символом ; или в несколько строк»; ячейка3;

Если же в самой ячейке встречаются кавычки (”), то они удваиваются.

Например:
Это»кавычки; => Это»»кавычки;

Что делает стандартная функция экспорта в CSV в PHP

Функция fputcsv ($csv_file , $array, $delimiter = ‘,’, $enclosure = ‘»‘ ) выполняет экспорт массива $array в файл $csv_file. При этом в качестве разделителя по умолчанию используя запятую ($delimiter = ‘,’) ,а в качестве обрамляющего символа – кавычки ($enclosure = ‘»‘).

Казалось бы, чтобы записать данные в формат CSV для MS Excel нужно всего лишь установить $delimiter = ‘;’, а $enclosure оставить равным кавычкам (“), но в реальности случаются ошибки интерпретации файла Экселем.

Вот в чем подвох: функция fputcsv в качестве экранирующего символа – обратный слеш (). И это изменить никак нельзя. То есть, если вы будете писать данные вида лалал”лала, то при записи в файл этот символ кавычек не удвоится, потому что он экранирован обратным слешем, а значит, Эксель посчитает его границей ячейки, хотя это не так.

Выход: использовать свою функцию экспорта в CSV, далее будет приведен ее текст.

Что делает стандартная функция импорта в CSV в PHP

В PHP функция импорта из CSV-фала fgetcsv($csv_file, $length = 0, $delimiter = ‘,’, $enclosure = ‘»‘, $escape = ‘\’) импортирует из CSV-файла $csv_file строка максимальной длины $length, если = 0, значит, она может быть любой. По умолчанию в качестве разделителя использует символ запятой (,), в качестве обрамляющего символа – кавычки («), и символ экранирования – обратный слеш ().

Начиная с PHP версии 5.3 символ экранирования в этой функции можно задавать свой.

Чтобы экспортировать данные с помощью PHP в формат CSV для Экселя, достаточно ко всему прочему в качестве экранирующего символа установить кавычки. То есть $delimiter = ‘;’, $enclosure = ‘»‘, $escape = ‘»‘.

Итоговые функции работы с CSV

Как открыть Экселем CSV-файл в кодировке UTF-8

Чтобы Excel нормально открывал CSV-файлы в кодировке UTF-8 не достаточно просто записывать туда данные этой кодировке. Чтобы «подсказать» Экселю использовать юникод принято в начало файла вставлять 3х байтную последовательность: EF BB BF. Это не есть официальное решение, это просто особенность открытия Экселем CSV-файлов.

Для наглядности приведем кусок кода для PHP:

Далее уже экспортируем данные в кодировке UTF-8 при помощи функции my_fputcsv(). Excel отлично открывает такие файлы.

Важно! Несмотря на то, что файл откроется в кдировке utf-8, Excel его сохранит все равно в кодировке windows-1251.

Источник

CSV Export/Import with PHPExcel

Could you please guide me or provide me with some sample codes for performing CSV export and import using the PHPExcel library?

Excel export and import is fine but I need CSV export/import as well. I have other means of CSV export and import, but can it be done via PHPExcel also?

3 Answers 3

To import a CSV file into a PHPExcel object

To export a CSV file from a PHPExcel object

EDIT

How to read through the rows and cells:

How to write to a PHPExcel object: You don’t say where your data comes from: here’s how to do it from a MySQL Query

I been seeking the same thing. Excel CSV dosn’t always use the quote separators and escapes the quotes using «» because the algorithm was probably made back the 80’s or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval’d code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

. Now bob can do his spreadsheets

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

csv to excel conversion

Is there a way to convert csv file to excel file upon request through apache/.htaccess

6 Answers 6

PHPExcel is deprecated. You must use PhpSpreadsheet.

With PhpSpreadsheet, you can convert csv to xlsx by the following code:

Note: PHPExcel is now listed as DEPRECATED.

Users are directed to PhpSpreadsheet.

This one worked for me like a charm ! Cheers .

Yes, since apache is open-source, you can modify the .htaccess parser to call a library to convert your CSV files into excel files. But I don’t think this is what you’re looking for. :-).

I think really what you need is a dynamic web site. Then you can use PHP or any supported language to do what you need to do.

There is a project in sourceforge that does this conversion:

But for the conversion you need to make a dynamic page in apache (in python, php. )

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to convert CSV file to Excel in PHP

EasyXLS Excel library can be used to convert Excel files with PHP on Windows, Linux, Mac or other operating systems. The integration vary depending on the operating system or if .NET Framework or Java is chosen:

1. EasyXLS on Windows using .NET Framework (COM+) with PHP

2. EasyXLS on Linux, Mac, Windows using Java with PHP

EasyXLS on Windows using .NET Framework (COM+) with PHP

If you opt for the COM+ version of EasyXLS, be sure that you have EasyXLS installed and registered on your machine.

Step 1: Download and install EasyXLS Excel Library for COM+

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Verify if COM and .NET extension is enabled in PHP

Check PHP.ini for [COM_DOT_NET] extension.

See also

How to enable COM and .NET extension in PHP?

Step 3: Verify if EasyXLS is registered

Check if EasyXLS component is present in Component Services.

See also

How to verify if EasyXLS is registered?

Step 4: Run PHP code that converts CSV file to Excel

Execute the following PHP code that converts CSV file to Excel.

Overloaded methods
For methods with same name but different parameters, only the first method overload retains the original name. Subsequent overloads are uniquely renamed by appending to the method name ‘_2’, ‘_3’, etc (method, method_2, method_3), an integer that corresponds to the order of declaration that can be found in EasyXLS.h, a file that comes with EasyXLS installation.

EasyXLS on Linux, Mac, Windows using Java with PHP

If you opt for the Java version of EasyXLS, a similar code as above requires PHP/Java Bridge between PHP and Java.

Step 1: Download EasyXLS Excel Library for Java

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Install PHP/Java Bridge

Step 3: Setup EasyXLS library in Tomcat

Copy EasyXLS.jar into Tomcat installation path, lib folder.

Step 4: Run PHP code that converts CSV file to Excel

Execute the following PHP code that converts CSV file to Excel.

Источник

How to handle CSV files with PHP

Published May 09, 2018

In this tutorial, we’ll explain how PHP can handle CSV files. Once you learn how to handle CSV files, you can upload entire Excel files to a database, and execute the logic enabled by the PHP langugae.

In this tutorial we’ll learn:

  1. How to convert Excel files to CSV files
  2. How to parse a CSV file into PHP array

Joseph Benharosh is a full stack web developer and the author of the eBook The essentials of object oriented PHP.

How to convert Excel files to CSV files

In this tutorial, we’ll work with a Google sheet that contains information about car models. Including their name, country of origin and price in dollars.

* If you want to start working with an Excel file you can import it into a Google sheet.

Here’s how the original Google sheet looks:

To convert the document to CSV, we’ll download it as a comma-separated values (csv) file:

The result is a CSV file, with the fields in each row separated by commas. Here’s how it looks in the Notepad++ text editor:

You are welcome to download the csv file that we’re going to use in the following sections of the tutorial.

How to handle CSV file with PHP

The function that parses the CSV file is fgetcsv , with the following syntax:

  1. The name of the CSV file
  2. 1000 — The length of the longest line
  3. «,» — Optional delimiter parameter. The default is, of course, comma

In order to use the fgetcsv function, we need to first open the file for reading with fopen , and end the code by closing the file with fclose . In between, we use a loop inside of which we parse each CSV row separately.

Let’s write the code.

The first step is opening the file for reading with fopen :

We use the «r» mode in order to open the file for reading.

The $h variable is the handle that holds the data from the file.

The second step is reading the file line-by-line using fgetcsv , and converting each row individually into an array that we call $data .

fgetcsv includes the handle ( $h ), from the previous section, and in order to read all the lines, we’ll run in it inside a while loop.

Lastly, we need to close the file.

Let’s combine the 3 steps:

How to convert a CSV file into a PHP multidimensional array

The following code produces a multidimensional array ( $ the_big_array ), with each of its items being made of an array that was converted from a single line in the CSV file.

And here is the array that the code in this tutorial generated from the CSV file:

Conclusion

This concludes our experimenting with parsing CSV file into PHP array. You can take the result and feed it into the database or perform any sort of logic with PHP.

Источник

I been seeking the same thing. Excel CSV dosn’t always use the quote separators and escapes the quotes using «» because the algorithm was probably made back the 80’s or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval’d code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

    function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
    // SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
    // AUTHOR: tgearin2@gmail.com
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array(); $fields=array(); $csv="";
        $escapes=array('r', 'n', 't', '\', '"');  //two byte escape codes
        $escapes2=array("r", "n", "t", "\", """); //actual code

        if($mode=='EXCEL')// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="rn"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="rn"; }

          $csv=""; $i=-1; $i2=0; $imax=count($rows);

          while( $i < $imax )
          {
            // get field names
            if($i == -1)
             { $row=$rows[0];
               if($fmt=='2D_FIELDNAME_ARRAY')
                { $i2=0; $i2max=count($row);
                  while( list($k, $v) = each($row) )
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if($fmt='2D_NUMBERED_ARRAY')
                { $i2=0; $i2max=(count($rows[0]));
                  while($i2<$i2max)
                   { $fields[$i2]=$i2;
                     $i2++;
                   }
                }

               if($headerrow==true) { $row=$fields; }
               else                 { $i=0; $row=$rows[0];}
             }
            else
             { $row=$rows[$i];
             }

            $i2=0;  $i2max=count($row); 
            while($i2 < $i2max)// numeric loop (order really matters here)
            //while( list($k, $v) = each($row) )
             { if($i2 != 0) $csv=$csv.$delim;

               $v=$row[$fields[$i2]];

               if($mode=='EXCEL') //EXCEL 2quote escapes
                    { $newv = '"'.(str_replace('"', '""', $v)).'"'; }
               else  //STANDARD
                    { $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
               $csv=$csv.$newv;
               $i2++;
             }

            $csv=$csv."rn";

            $i++;
          }

         return $csv;
       }

    function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
     { // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
       // AUTHOR: tgearin2@gmail.com
       // RELEASED: 9/21/13 BETA
       //SWMessage("SW_ExplodeCSV() - CALLED HERE -");
       $rows=array(); $row=array(); $fields=array();// rows = array of arrays

       //escape code = ''
       $escapes=array('r', 'n', 't', '\', '"');  //two byte escape codes
       $escapes2=array("r", "n", "t", "\", """); //actual code

       if($mode=='EXCEL')
        {// escape code = ""
          $delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="rn";
        }
       else //mode=STANDARD 
        {// all fields enclosed
          $delim=','; $enclos='"'; $rowbr="rn";
        }

       $indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
       $rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
       $headerflg=0; $quotedflg=0;
       $i=0; $i2=0; $imax=strlen($csv);   

       while($indxf < $imax)
         {
           //find first *possible* cell delimiters
           $indxl=strpos($csv, $delim, $indxf);  if($indxl===false) { $indxl=$imax; }
           $encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
           $rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }

           if(($encindxf>$indxl)||($encindxf>$rowindxl))
            { $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }
           else 
            { //find cell enclosure area (and real cell delimiter)
              $quoteflg=1;
              $enc=$encindxf; 
              while($enc<$indxl) //$enc = next open quote
               {// loop till unquoted delim. is found
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
                 $encindxl=$enc; //last close quote
                 $indxl=strpos($csv, $delim, $enc+1); if($indxl===false)  { $indxl=$imax; }//last delim.
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
                 if(($indxl==$imax)||($enc==$imax)) break;
               }
              $rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }

           if($quoteflg==0)
            { //no enclosured content - take as is
              $colflg=1;
              //get cell 
             // $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
              $cell=substr($csv, $indxf, ($indxl-$indxf));
            }
           else// if($rowindxl > $encindxf)
            { // cell enclosed
              $colflg=1;

             //get cell - decode cell content
              $cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);

              if($mode=='EXCEL') //remove EXCEL 2quote escapes
                { $cell=str_replace($esc_enclos, $enclos, $cell);
                }
              else //remove STANDARD esc. sceme
                { $cell=str_replace($escapes, $escapes2, $cell);
                }
            }

           if($colflg)
            {// read cell into array
              if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
               { $row[$fields[$colcnt]]=$cell; }
              else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
               { $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;

              $colcnt++; $colflg=0; $cell="";
              $indxf=$indxl+1;//strlen($delim);
            }
           if($rowflg)
            {// read row into big array
              if(($headerrow) && ($headerflg==0))
                {  $fields=$row;
                   $row=array();
                   $headerflg=1;
                }
              else
                { $rows[$rowcnt]=$row;
                  $row=array();
                  $rowcnt++; 
                }
               $colcnt=0; $rowflg=0; $cell="";
               $rowindxf=$rowindxl+2;//strlen($rowbr);
               $indxf=$rowindxf;
            }

           $i++;
           //SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt."   rowcnt = ".$rowcnt."   indxf = ".$indxf."   indxl = ".$indxl."   rowindxf = ".$rowindxf);
           //if($i>20) break;
         }

       return $rows;
     }

…Now bob can do his spreadsheets

В статье приведены два примера конвертации фалов csv в xlsx, алгоритм следующий:

  • Файл открывается с помощью fopen() и построчно преобразуем функцией fgetcsv() в массив, в качестве разделителя обычно используется ,
  • Из полученного массива сформируется xlsx файл с помощью библиотеки PHPExcel.

1

Загрузка файлов через форму

HTML форма

<form action="" method="post" enctype="multipart/form-data">
	<div class="control-group">	
		<label class="control-label">Файл csv</label>
		<div class="controls">
			<input type="file" name="file">
		</div>
	</div>

	<button type="submit">Отправить</button>		
</form>

HTML

Обработчик формы

if (!empty($_FILES['file']['tmp_name'])) {
	if (pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) == 'csv') {
		// Чтение файла в массив.
		$list = array();
		if (($fp = fopen($_FILES['file']['tmp_name'], 'r')) !== false) {
			while (($data = fgetcsv($fp, 0, ',')) !== false) {
				$list[] = $data;
			}
			fclose($fp);
		}
			
		// Подключение PHPExcel.
		require_once __DIR__ . '/PHPExcel/Classes/PHPExcel.php';
		require_once __DIR__ . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
		$xls = new PHPExcel();
				
		// В первый лист.
		$xls->setActiveSheetIndex(0);
		$sheet = $xls->getActiveSheet();

		// Формирование XLSX.
		$line = 0;
		foreach ($list as $line => $item) {
			$line++;
			foreach ($item as $col => $row) {
				$sheet->setCellValueByColumnAndRow($col, $line, $row);
			}
		}
				
		// Отдача файла в браузер.
		$filename = basename($_FILES['file']['name'], '.csv') . '.xlsx';

		header('Expires: Mon, 1 Apr 1974 05:00:00 GMT');
		header('Last-Modified: ' . gmdate('D,d M YH:i:s') . ' GMT');
		header('Cache-Control: no-cache, must-revalidate');
		header('Pragma: no-cache');
		header('Content-type: application/vnd.ms-excel');
		header('Content-Disposition: attachment; filename=' . $filename);

		$objWriter = new PHPExcel_Writer_Excel2007($xls);
		$objWriter->save('php://output'); 
		exit;
	}
}

PHP

2

Преобразование на сервере

$file = __DIR__ . '/list.csv';

// Чтение файла в массив.
$list = array();
if (($fp = fopen($file, 'r')) !== false) {
	while (($data = fgetcsv($fp, 0, ',')) !== false) {
		$list[] = $data;
	}
	fclose($fp);
}
	
// Подключение PHPExcel.
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel.php';
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
$xls = new PHPExcel();

// В первый лист.
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

// Формирование XLSX.
$line = 0;
foreach ($list as $line => $item) {
	$line++;
	foreach ($item as $col => $row) {
		$sheet->setCellValueByColumnAndRow($col, $line, $row);
	}
}

// Сохранение файла.
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save(__DIR__ . '/' . basename($file, '.csv') . '.xlsx');

PHP

CSV очень удобный формат с точки зрения генерации, поскольку он очень просто устроен. В этой заметке разберемся как устроены файлы с расширением .csv, как их создавать и разбирать (парсить) в PHP. Делается это очень просто.

Ниже приведены простые PHP функции для создания и парсинга csv файлов. Никаких библиотек — для CSV это лишнее!

Формат CSV

Чтобы понимать суть вещей, нужно разобраться в спецификации CSV файлов, как устроен формат. Давайте коротко…

CSV (Comma-Separated Values — значения, разделённые запятыми) — текстовый формат, предназначенный для представления табличных данных.

  • Каждая строка файла — это одна строка таблицы.

  • Разделителем значений колонок является символ: , (запятая). Для русского языка используется ; (точка с запятой), потому что в русском запятая используется в дробных числах.

  • Значения, содержащие зарезервированные символы: " , ; rn или n или r (двойная кавычка, запятая, точка с запятой, новая строка) обрамляются двойными кавычками ".

  • Если в значении встречаются двойные кавычки ", то они должны выглядеть как двое кавычек подряд "".

  • Строка файла может разделяться символами: rn или n.

Это все что нужно знать, чтобы работать с CSV!

Пример для рус. языка:

1965;Пиксель;E240 – формальдегид (опасный консервант)!;"красный, зелёный, битый";3000,00
1965;Мышка;"А правильней использовать ""Ёлочки""";;4900,00
"Н/д";Кнопка;Сочетания клавиш;"MUST USE! Ctrl, Alt, Shift";4799,00

Пример для англ. языка:

1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture «Extended Edition»","",4900.00
1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00

Wiki-справка

Большинство программ под CSV понимают более общий формат DSV (delimiter-separated values — значения разделённые разделителем), допускающий использование иных символов в качестве разделителя. В частности, в русской и других локалях запятая по умолчанию зарезервирована под десятичный разделитель. Поэтому как разделитель используется точка с запятой или табуляция (формат TSV).

Сегодня под CSV понимают набор значений, разделенных какими угодно разделителями, в какой угодно кодировке с какими угодно окончаниями строк. Это значительно затрудняет перенос данных из одних программ в другие, несмотря на всю простоту формата.

Создание CSV файла в PHP

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

Важным моментом, является кодировка файла. Для корректного отображения кириллицы следует использовать кодировку cp1251 (windows-1251).

Разделитель колонок

Для русского языка символом-разделителем является ; (точка с запятой). Для англ. , (запятая).

Строки содержащие спец символы: " , ; rn или n или r должны быть в двойных кавычках "строка".

Двойные кавычки внутри строки, нужно «очистить» поставив перед кавычкой еще одну такую же кавычку: строка "csv" превратиться в "строка ""csv""". Обрамление в кавычки нужно, чтобы можно было внутри значений колонок использовать разделители ;, , и не переживать что что-то сломается при чтении файла.

Разделитель строк

Для разделения строк в csv файлах можно использовать rn (возврат каретки и перенос строки, CR LF). В этом случае, если нужен перенос строки внутри значения колонки, то там используется просто n.

Также, для разделения строки, может использоваться просто n (перенос строки, LF). В этом случае, перенос строки внутри значения колонки должен обозначаться как r (возврат каретки CR).

Функция для создания CSV файла
/**
 * Создает CSV файл из переданных в массиве данных.
 *
 * @param array  $create_data   Массив данных из которых нужно созать CSV файл.
 * @param string $file          Путь до файла 'path/to/test.csv'. Если не указать, то просто вернет результат.
 * @param string $col_delimiter Разделитель колонок. Default: `;`.
 * @param string $row_delimiter Разделитель рядов. Default: `rn`.
 *
 * @return false|string CSV строку или false, если не удалось создать файл.
 *
 * @version 2
 */
function kama_create_csv_file( $create_data, $file = null, $col_delimiter = ';', $row_delimiter = "rn" ){

	if( ! is_array( $create_data ) ){
		return false;
	}

	if( $file && ! is_dir( dirname( $file ) ) ){
		return false;
	}

	// строка, которая будет записана в csv файл
	$CSV_str = '';

	// перебираем все данные
	foreach( $create_data as $row ){
		$cols = array();

		foreach( $row as $col_val ){
			// строки должны быть в кавычках ""
			// кавычки " внутри строк нужно предварить такой же кавычкой "
			if( $col_val && preg_match('/[",;rn]/', $col_val) ){
				// поправим перенос строки
				if( $row_delimiter === "rn" ){
					$col_val = str_replace( [ "rn", "r" ], [ 'n', '' ], $col_val );
				}
				elseif( $row_delimiter === "n" ){
					$col_val = str_replace( [ "n", "rr" ], 'r', $col_val );
				}

				$col_val = str_replace( '"', '""', $col_val ); // предваряем "
				$col_val = '"'. $col_val .'"'; // обрамляем в "
			}

			$cols[] = $col_val; // добавляем колонку в данные
		}

		$CSV_str .= implode( $col_delimiter, $cols ) . $row_delimiter; // добавляем строку в данные
	}

	$CSV_str = rtrim( $CSV_str, $row_delimiter );

	// задаем кодировку windows-1251 для строки
	if( $file ){
		$CSV_str = iconv( "UTF-8", "cp1251",  $CSV_str );

		// создаем csv файл и записываем в него строку
		$done = file_put_contents( $file, $CSV_str );

		return $done ? $CSV_str : false;
	}

	return $CSV_str;

}

Теперь, чтобы сгенерировать CSV файл нужно использовать эту функцию так:

$create_data = array(
	array(
		'Заголовок 1',
		'Заголовок 2',
		'Заголовок 3',
	),
	array(
		'строка 2 "столбец 1"',
		'4799,01',
		'строка 2 "столбец 3"',
	),
	array(
		'"Ёлочки"',
		4900.01,
		'красный, зелёный',
	)
);

echo kama_create_csv_file( $create_data, THEME_PATH .'csv_file.csv' );

/* Получим

Заголовок 1;Заголовок 2;Заголовок 3
"строка 2 ""столбец 1""";"4799,00";"строка 2 ""столбец 3"""
"""Ёлочки""";4900.01;"красный, зелёный"

*/

Чтение CSV файла в PHP

Когда нужно получить данные из CSV файла, т.е. разобрать его и получить данные в переменную, можно использовать встороенную в PHP функцию str_getcsv().

Есть еще функция fgetcsv(), но она оказалась капризной и не всегда работает как нужно (может перепутать переносы строк)…

Вариант на базе функции str_getcsv():

/**
 * Читает CSV файл и возвращает данные в виде массива.
 *
 * @param string $file_path      Путь до csv файла.
 * @param array  $file_encodings
 * @param string $col_delimiter  Разделитель колонки (по умолчанию автоопределине)
 * @param string $row_delimiter  Разделитель строки (по умолчанию автоопределине)
 *
 * @version 6
 */
function kama_parse_csv_file( $file_path, $file_encodings = ['cp1251','UTF-8'], $col_delimiter = '', $row_delimiter = '' ){

	if( ! file_exists( $file_path ) ){
		return false;
	}

	$cont = trim( file_get_contents( $file_path ) );

	$encoded_cont = mb_convert_encoding( $cont, 'UTF-8', mb_detect_encoding( $cont, $file_encodings ) );

	unset( $cont );

	// определим разделитель
	if( ! $row_delimiter ){
		$row_delimiter = "rn";
		if( false === strpos($encoded_cont, "rn") )
			$row_delimiter = "n";
	}

	$lines = explode( $row_delimiter, trim($encoded_cont) );
	$lines = array_filter( $lines );
	$lines = array_map( 'trim', $lines );

	// авто-определим разделитель из двух возможных: ';' или ','.
	// для расчета берем не больше 30 строк
	if( ! $col_delimiter ){
		$lines10 = array_slice( $lines, 0, 30 );

		// если в строке нет одного из разделителей, то значит другой точно он...
		foreach( $lines10 as $line ){
			if( ! strpos( $line, ',') ) $col_delimiter = ';';
			if( ! strpos( $line, ';') ) $col_delimiter = ',';

			if( $col_delimiter ) break;
		}

		// если первый способ не дал результатов, то погружаемся в задачу и считаем кол разделителей в каждой строке.
		// где больше одинаковых количеств найденного разделителя, тот и разделитель...
		if( ! $col_delimiter ){
			$delim_counts = array( ';'=>array(), ','=>array() );
			foreach( $lines10 as $line ){
				$delim_counts[','][] = substr_count( $line, ',' );
				$delim_counts[';'][] = substr_count( $line, ';' );
			}

			$delim_counts = array_map( 'array_filter', $delim_counts ); // уберем нули

			// кол-во одинаковых значений массива - это потенциальный разделитель
			$delim_counts = array_map( 'array_count_values', $delim_counts );

			$delim_counts = array_map( 'max', $delim_counts ); // берем только макс. значения вхождений

			if( $delim_counts[';'] === $delim_counts[','] )
				return array('Не удалось определить разделитель колонок.');

			$col_delimiter = array_search( max($delim_counts), $delim_counts );
		}

	}

	$data = [];
	foreach( $lines as $key => $line ){
		$data[] = str_getcsv( $line, $col_delimiter ); // linedata
		unset( $lines[$key] );
	}

	return $data;
}

Использование:

$data = kama_parse_csv_file( '/path/to/file.csv' );
print_r( $data );

Конвертация .lsx, .xlsx файла в .csv

Чтобы перевести Excel файл в CSV, нужно открыть его в Excel и сохранить в формате .csv:

Если такую конвертацию нужно сделать программно, смотрите в сторону онлайн конвертеров с API или готовых библиотек.

Сталкивались с такой задачей и знаете более универсальный способ? Прошу поделиться в комментариях.

Я столкнулся и потратил несколько часов перебирая всякий не универсальный «мусор» из гугла — то одно не работает, то другое, то библиотеку нужно ставить «хитро-мудрую»… Так и появилась эта заметка…

Как отдать сгенерированный CSV файл для загрузки

Для этого нужно установить заголовки:

<?php

header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename="file.csv"' );

$create_data = [
	[
		'Заголовок 1',
		'Заголовок 2',
		'Заголовок 3',
	],
];

echo kama_create_csv_file( $create_data );

by Vincy. Last modified on October 29th, 2022.

CSV is one of the familiar file formats and used widely by programmers for handling data. The simplicity of the format and human readable form made it so popular. CSV stands for Comma-Separated Values. In earlier days, the delimiter was only a comma (,) and so the name CSV. Nowadays, CSV files use tab-demitted row data too.

To handle CSV with PHP, we must be aware there is excellent support in-built with core PHP. Knowledge about those built-in library and functions will he handy in handling CSV files.

CSV PHP

What is inside?

In this article, we will see about about how to handle CSV using PHP  with suitable examples.

  1. CSV file format and MIME type
  2. How to convert PHP Array to CSV?
  3. CSV file data validation
  4. How to import large CSV files?
  5. How to split large CSV files and process using PHP?
  6. How to read encoded CSV files with special characters?
  7. Convert CSV file to HTML table using PHP
  8. Process CSV file with comma data values using PHP
  9. Export database records to CSV in a generic way
  10. How to export CSV using fputcsv?
  11. Download as CSV File via browser using Content-Type
  12. Read CSV using PHP built-in functions

This will serve you as a comprehensive tutorial that discusses all aspects of CSV file handling with PHP. When you need to handle structured data then using JSON data and handling it with PHP will be a better choice.

CSV file format and MIME type

Let us start with CSV format and MIME type conventions. The common formats and MIME type for the CSV files are discussed here with the reference of the RFC 4180 documentation.

CSV Format Definition

These are the general definitions for a valid CSV format.

  • Each row is separated or delimited by a line break (CRLF). For example:
            col_11,col_12,col_13 CRLF
            col_21,col_22,col_23 CRLF
    
  • The last row of the CSV file may or may not have a line break. For example:
            col_11,col_12,col_13 CRLF
            col_21,col_22,col_23
    
  • CSV data may contain an optional header line at the beginning in the same format as other rows. For example:
           column_name1,column_name2,column_name3 CRLF
           col_11,col_12,col_13 CRLF
           col_21,col_22,col_23
    
  • The count of the comma-separated field names in the header must be the same as the count of the comma-separated values in rest of the rows in the CSV file. For example:
           column_name1,column_name2,column_name3 CRLF
           col_11,col_12,col_13 CRLF
           col_21,col_22,col_23
    
  • Each field the rows may be enclosed by Double Quotes(“). But it is optional. Fields not enclosed by double quote may not contain the double quotes special character as part of it. For example:
           "col_11","col_12","col_13" CRLF
           col_21,col_22,col_23
    
  • Fields containing double quotes (“), Line Break (CRLF) and Comma must be enclosed with double quotes. For example:
           "col_""11","col_"CRLF
           12",col_13 CRLF
           col_21,col_22,col_23
    
  • Fields containing double quotes (“), Line Break (CRLF) and Comma must be enclosed with double quotes. For example:
           "col_11","col_"CRLF
           12",col_13 CRLF
           col_21,col_22,col_23
    
  • If Fields enclosed by double quotes (“) contain double quotes character then the double quotes inside the field must be preceded with another double quote as an escape sequence. For example:
           "col_""11","col_12",col_13 CRLF
           col_21,col_22,col_23
    

The standard exclusive MIME type text/csv is registered by the RFC 4180. Before that, various MIME types like “text/tab-separated-values” type were used by various programs or OS for the CSV format.

If you want to learn more about the CSV format and MIME types, the RFC 4180 document has more information.

How to convert PHP Array to CSV?

There are many possible ways in PHP to convert an array data into CSV format. PHP contains in-built functions like fputcsv() for doing this conversion.

The following code uses custom PHP function str_putcsv() to get the array data and put it into the file target as specified. This custom function uses PHP built-in fputcsv() on each array iteration.

<?php

function arrayToCSV($inputArray)
{
    $csvFieldRow = array();
    foreach ($inputArray as $CSBRow) {
        $csvFieldRow[] = str_putcsv($CSBRow);
    }
    $csvData = implode("n", $csvFieldRow);
    return $csvData;
}

function str_putcsv($input, $delimiter = ',', $enclosure = '"')
{
    // Open a memory "file" for read/write
    $fp = fopen('php://temp', 'r+');
    // Write the array to the target file using fputcsv()
    fputcsv($fp, $input, $delimiter, $enclosure);
    // Rewind the file
    rewind($fp);
    // File Read
    $data = fread($fp, 1048576);
    fclose($fp);
    // Ad line break and return the data
    return rtrim($data, "n");
}

$inputArray = array(
    array("First Name", "Last Name", "Identification Number"),
    array("Kim","Thomas","8001"),
    array("Jeffery","Robert","8021"),
    array("Helan","Albert","8705")
);
print "<PRE>";
print $CSVData = arrayToCSV($inputArray);
?>

I have printed the converted output data to the browser. The CSV output is,

PHP Array to CSV Conversion Output

CSV file data validation

Generally, validation on a CSV file will be done to check whether it has the standard format definition. The following conditions have to be applied to a CSV input file to check whether it is valid or not.

  • To check if the input file is with the proper CSV file extension and within the size limit.
  • To check if the count of comma-separated values in all rows are same.
  • To check if the row data containing allowed special characters with proper escape sequences.

Added to that, you can add additional validation based on your application requirement. For example,

  • To check if the CSV row field contains data in an expected format. For example, if a phone_number field contains numeric data with allowed characters.
  • To check if the fields are in the correct order as per your application requirement.
  • To check if the mandatory fields are not empty.

This PHP code shows how to apply CSV validation on an uploaded file. In a previous tutorial, we have seen how to validate an uploaded image file in PHP.

In this script, the validation made to check the CSV file extension, size. Once it is done, we need to handle CSV with PHP to check the field count in all the CSV rows.

<?php
if (isset($_POST["upload"])) {
    
    // Get file extension
    $file_extension = pathinfo($_FILES["file-input"]["name"], PATHINFO_EXTENSION);
    // Validate file input to check if is not empty
    if (! file_exists($_FILES["file-input"]["tmp_name"])) {
        $response = array(
            "type" => "error",
            "message" => "File input should not be empty."
        );
    } // Validate file input to check if is with valid extension
    else if ($file_extension != "csv") {
            $response = array(
                "type" => "error",
                "message" => "Invalid CSV: File must have .csv extension."
            );
            echo $result;
        } // Validate file size
    else if (($_FILES["file-input"]["size"] > 2000000)) {
            $response = array(
                "type" => "error",
                "message" => "Invalid CSV: File size is too large."
            );
        } // Validate if all the records have same number of fields
    else {
        $lengthArray = array();
        
        $row = 1;
        if (($fp = fopen($_FILES["file-input"]["tmp_name"], "r")) !== FALSE) {
            while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
                $lengthArray[] = count($data);
                $row ++;
            }
            fclose($fp);
        }
            
        $lengthArray = array_unique($lengthArray);
        
        if (count($lengthArray) == 1) {
            $response = array(
                "type" => "success",
                "message" => "File Validation Success."
            );
        } else {
            $response = array(
                "type" => "error",
                "message" => "Invalid CSV: Count mismatch."
            );
        }
    }
}
?>

CSV Validation Script

<form id="frm-upload" action="" method="post"
    enctype="multipart/form-data">
    <div class="form-row">
        <div>Choose file:</div>
        <div>
            <input type="file" class="file-input" name="file-input">
        </div>
    </div>

    <div class="button-row">
        <input type="submit" id="btn-submit" name="upload"
            value="Upload">
    </div>
</form>
<?php if(!empty($response)) { ?>
<div class="response <?php echo $response["type"]; ?>
    ">
    <?php echo $response["message"]; ?>
</div>
<?php }?>

If the validation process is not returning TRUE then the error message will be displayed to the user as shown in the below screenshot.

CSV Validation Script

How to import large CSV files?

Importing a large CSV file using PHP file handling functions may not be an efficient way of doing it. If the execution time exceeds the configured max_execution_time limit then the import will not be completed.

While processing large CSV file import, there are ways like command line execution, query execution and more. In this section, I will show how to import a large CSV file using MySQL LOAD DATA statement. If you can this LOAD, then this is the better choice as it gives the best performance.

<?php 
$conn = mysqli_connect("localhost", "root", "test", "blog_samples");
$query = "LOAD DATA INFILE 'input.csv' INTO TABLE tbl_student_master IGNORE 1 LINES";
if (!mysqli_query($conn, $query)) {
    printf("Errormessage: %sn", mysqli_error($conn));
}
?>

Before running this program, make sure that you have created the required target database and table. Import the following SQL script to process import by running this example in your environment.

--
-- Table structure for table `tbl_student_master`
--

CREATE TABLE `tbl_student_master` (
  `unique_id` int(11) NOT NULL,
  `first_name` varchar(55) NOT NULL,
  `last_name` varchar(55) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_student_master`
--
ALTER TABLE `tbl_student_master`
  ADD PRIMARY KEY (`unique_id`);
COMMIT;

Note: If the –secure-file-priv option is enabled in your MySQL configuration, then this program will work only if the input CSV file is located in the directory as specified in the –secure-file-priv settings.

How to split large CSV files and process using PHP?

In a previous tutorial, we have seen how to split an excel file into multiple files. Splitting will be required while dealing with large Excel or CSV file.

In this section, I am showing how to split a CSV file into multiple files. I have used PHP RegexIterator and SplFileObject classes for implementing splitting on an input CSV file.

The RegexIterator is the built-in PHP class that inherits FilterInheritor class to filter based on regular expression. It accepts the input data, regex pattern and mode of operations and more parameters.

The  SplFileObject class which gives an object-oriented interface for a file. Using this the target object is created to put the splitted records into the target.

<?php
$rowAry = new RegexIterator(new SplFileObject('input.csv'), '/n/', RegexIterator::SPLIT);
$header = "";
foreach ($rowAry as $i => $row) {
    // IF the input CSV has header (column_name) row
    if ($i == 0) {
        $header = $row[0];
    } else {
        $filename = "output_$i.csv";
        $myfile = fopen($filename, "w");
        $target = new SplFileObject($filename, 'w');
        if (! empty($header)) {
            $target->fwrite($header . "n");
        }
        $target->fwrite($row[0]);
    }
}
?>

How to read encoded CSV files with special characters?

If the input CSV contains non-english data, the CSV file parsing will behave as expected. Either it will return error like “Invalid argument” or it will output jumbled character as the result of the CSV read operation.

This issue could be resolved by setting the charset while reading CSV. In the below script, the PHP iconv function is used to set the input and output charset for reading the actual data from the CSV.

<?php
function convert( $str ) {
    return iconv( "UTF-8", "UTF-8", $str );
}

if (($fp = fopen('input.csv', "r")) !== FALSE) {
    while (($row = fgetcsv($fp)) !== false) {
        $rowArray = array_map( "convert", $row );
        $rowCSV[] = implode(",", $rowArray);
    }
    fclose($fp);
    $csvData = implode("n", $rowCSV);
    print $csvData;
}
?>

Convert CSV file to HTML table using PHP

For converting the CSV file into a HTML format, the table rows markup has to be created during the row by row iteration of the CSV.

With the reference of the previous examples that we have seen above, it is an easy job to create HTML for the CSV data.

Below code shows how to generate HTML table markup and display the CSV data into it. It iterates the CSV file uploaded via an HTML form and it is parsed to get the row data.

The parsed row data is put into the table columns by using PHP echo statements. The table header could be identified by using the loop iteration index. Hence, the header data is differentiated from the other rows using CSS.

<?php
if(!empty(isset($_POST["upload"]))) {
    if (($fp = fopen($_FILES["file-input"]["tmp_name"], "r")) !== FALSE) {
    ?>
<table class="tutorial-table" width="100%" border="1" cellspacing="0">
<?php
    $i = 0;
    while (($row = fgetcsv($fp)) !== false) {
        $class ="";
        if($i==0) {
           $class = "header";
        }
        ?>
    <tr>
            <td class="<?php echo $class; ?>"><?php echo $row[0]; ?></td>
            <td class="<?php echo $class; ?>"><?php echo $row[1]; ?></td>
            <td class="<?php echo $class; ?>"><?php echo $row[2]; ?></td>
        </tr>
    <?php
        $i ++;
    }
    fclose($fp);
    ?>
    </table>
<?php
    $response = array("type" => "success", "message" => "CSV is converted to HTML successfully");
    } else {
        $response = array("type" => "error", "message" => "Unable to process CSV");
    }
}
?>
</div>
<?php if(!empty($response)) { ?>
<div class="response <?php echo $response["type"]; ?>
    ">
    <?php echo $response["message"]; ?>
</div>
<?php } ?>

CSV to HTML Conversion Output

The following screenshot shows the output of the HTML table generated by parsing the CSV file uploaded via the form.

CSV To HTML Conversion

Process CSV file with comma data values using PHP

As per the CSV specification “Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.

So, I have created an input.csv containing values with Comma(,) character. The file content will be as shown as below.

"Identification Number","First Name","Last Name"
8001,"Kim,",Thomas
8021,"Jeff,ery",Robert
8705,Helan,Albert

In the above CSV data, you can see that the values containing Comma are enclosed by the double quotes(“)

As like as the above example, we are going to use PHP fgetcsv() function to read and process the CSV file data containing Comma in its value.

As per the syntax of the fgetcsv() function, it receives character inputs for specifying the field delimiter, field enclosure and more.

As the default enclosure is the double quotes character, we need not specify those parameters while invoking fgetcsv().

Supply the CSV input having values with Comma to the CSV to HTML conversion script that we have seen in the above section. This will output the CSV data with Comma in the HTML format as shown below.

Process CSV Containing Values with Comma

Export database records to CSV in a generic way

While exporting a database, the backup file can be created in various formats SQL, CSV, Excel. In a previous tutorial, we have seen how to export a database to a CSV file.

For doing this database backup programmatically, we need to execute appropriate MySQL statements to extract the structure and the data.

By doing this, the backup will be ready with the database table’s create statements, insert queries dumped with data, statements for Indexes, auto increment and more. The PHP code for exporting database records to CSV is as follows.

<?php
$conn = mysqli_connect("localhost","root","test", "phppot_examples");

$query = "SELECT * FROM toy";
$result = mysqli_query($conn, $query);

$num_column = mysqli_num_fields($result);		

$csv_header = '';
for($i=0;$i<$num_column;$i++) {
    $csv_header .= '"' . mysqli_fetch_field_direct($result,$i)->name . '",';
}	
$csv_header .= "n";

$csv_row ='';
while($row = mysqli_fetch_row($result)) {
for($i=0;$i<$num_column;$i++) {
		$csv_row .= '"' . $row[$i] . '",';
}
	$csv_row .= "n";
}
?>

In this code, the database structure and data are extracted and prepared in the form of CSV string.

Then the prepared backup content can be downloaded to the browser by using PHP header() function with the specification if Content-Type. In the following sections, we will see how to download CSV by using Content-Type.

How to export CSV using fputcsv?

If you are only going to take the data backup instead of a complete database, then the fputcsv() function is enough. This function accepts the target CSV handle and the input array as it mandatory arguments.

The input array must contain the row of column names or column values. The following PHP code shows how to exports MySQL records to a CSV file using fputcsv().

In this code, the database column names and values are extracted row by row and put it into the target CSV. The target CSV handle is created before executing the fputcsv() function.

<?php
$conn = mysqli_connect("localhost", "root", "test", "phppot_examples");

$filename = "toy_csv.csv";
$fp = fopen('php://output', 'w');

$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='phppot_examples' AND TABLE_NAME='toy'";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_row($result)) {
	$header[] = $row[0];
}	

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);

$query = "SELECT * FROM toy";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_row($result)) {
	fputcsv($fp, $row);
}
exit;
?>

Download as CSV File via browser using Content-Type

In the above code, the PHP header() function is used to specify the Content-type, Content-disposition and more specifications. With these settings, the header will be sent to the browser with the CSV file attachment to be downloaded.

By adding the header() function with Content-type: application/csv then CSV file will be downloaded to the browser.

Read CSV using PHP built-in functions

PHP supports to read a CSV file by proving built-in functions. In this article, we have seen several examples to handle CSV with PHP functions like fgetcsv(), str_getcsv(). All these PHP functions are used in the above sections to read CSV file before processing it.

The fgetcsv() function is used to read the CSV file data with the reference of the file handle. The str_getcsv() will accept the CSV string instead of the file pointer. Then the CSV string will be parsed to read the data.

Conclusion

As the CSV(Comma-Separated Values) is one of the popularly used data handling formats and every programmer should be comfortable in handling CSV data. PHP provides the best support for handling CSV file and you should be aware of the functions available. Hope you have been introduced to all about CSV in PHP. If there is any topic missing, let me know it via the comments below and I will include that in the article.

↑ Back to Top

Понравилась статья? Поделить с друзьями:
  • To one word is too перевод
  • To not take sides word for
  • To not take seriously word
  • To not show emotion word
  • To not pay attention word that means