Home >Backend Development >PHP Tutorial >Summary of common operating methods for processing CSV table files with PHP
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('Content-Type: text/plain; charset=utf-8'); //导出CSV表格:数组转CSV $arr = array ( array('ab', 'cd'), array('"a,b"', '"c,d"'), ); $fp = fopen('file.csv', 'w'); foreach ($arr as $row) { //将一行格式化为CSV并写入文件指针 fputcsv($fp, $row); } fclose($fp); unset($arr); //导入CSV表格:CSV转数组 $fp = fopen('file.csv', 'r'); while ( ($row = fgetcsv($fp)) !== FALSE ) { //从文件指针中读入一行并解析CSV $arr[] = $row; } fclose($fp); var_export($arr);
Save as a separate file
download.php ; Chinese website!