Home  >  Article  >  Backend Development  >  Summary of common operating methods for processing CSV table files with PHP

Summary of common operating methods for processing CSV table files with PHP

高洛峰
高洛峰Original
2016-12-26 14:39:041092browse

If you want to use the online Excel table editing function, the parsing of Excel's xls file format is a problem. After all, this is the private patent format of Microsoft Office.
So if you want to do it, you should use the general csv (Comma Separated Value, comma separated values) format.
Various office software can recognize csv tables, which are actually tables with cells separated by specific delimiters (such as commas).
Take PHP as an example, fgetcsv reads the csv table and returns An array,
and then foreach outputs it as an HTML f5d188ed2c074f8b944552db028f98a1. This step can be achieved with just a few lines of code. It is very simple.
The workload mainly lies in the browser front-end. It is recommended that you use jQuery for DOM and AJAX Operation,
It is not difficult to achieve fine-grained double-click cell editing like phpMyAdmin, and then submit it through AJAX.
Or you can write the entire form at once $("form").serialize(); and then submit it through AJAX. .

A few rules for CSV tables:
1. Separate the cell contents of each row with commas.
2. If the content of the cell itself has a comma, the content of this cell It will be included in quotation marks.
3. If the content of the cell itself has quotation marks:
(1) The quotation mark is not at the beginning or end, the content of the cell will not be included in quotation marks.
(2) The quotation mark is in First or last, the content of this cell will be included in quotation marks, and the original first and last quotation marks will be escaped.

Read and write CSV

<?php
header(&#39;Content-Type: text/plain; charset=utf-8&#39;);
 
//导出CSV表格:数组转CSV
$arr = array (
  array(&#39;ab&#39;, &#39;cd&#39;),
  array(&#39;"a,b"&#39;, &#39;"c,d"&#39;),
);
$fp = fopen(&#39;file.csv&#39;, &#39;w&#39;);
foreach ($arr as $row) {
  //将一行格式化为CSV并写入文件指针
  fputcsv($fp, $row);
}
fclose($fp);
unset($arr);
 
//导入CSV表格:CSV转数组
$fp = fopen(&#39;file.csv&#39;, &#39;r&#39;);
while ( ($row = fgetcsv($fp)) !== FALSE ) {
  //从文件指针中读入一行并解析CSV
  $arr[] = $row;
}
fclose($fp);
var_export($arr);

Save as a separate file
download.php ; Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn