Summary of common PHP operations for processing CSV table files,
To edit an online Excel table, parsing the Excel xls file format is a problem. After all, this is the private patent format of Microsoft Office.
To do this, use the common csv (Comma Separated Value, Comma-Separated Value) format.
Various Office software can recognize csv tables, which are actually tables separated by specific delimiters (such as commas.
For PHP, fgetcsv reads the csv table and returns an array,
Then foreach outputs the result as an HTML <table>. This step can be implemented with several lines of code, which is very simple.
The workload mainly lies in the browser front-end. We recommend that you use jQuery to perform DOM and AJAX operations,
To achieve fine-grained double-click cell editing like phpMyAdmin, it is not difficult to submit AJAX,
Or $ ("form"). serialize () once the entire table is written, and AJAX can also be submitted.
CSV table rules:
1. Separate the content of cells in each row with commas.
2. If the content of a cell contains a comma, the content of the Cell will be enclosed in quotation marks.
3. If the content of a cell contains quotation marks:
(1) The quotation marks are not at the beginning or end. The content of this cell is not enclosed in quotation marks.
(2) When the quotation marks are at the beginning or end, the content of the Cell will be enclosed in quotation marks, and the original quotation marks at the beginning and end will be escaped.
Read/write CSV
<? Phpheader ('content-Type: text/plain; charset = UTF-8 '); // export a CSV table: convert an array to CSV $ arr = array (' AB ', 'cd'), array ('"a, B"', '"c, d"'),); $ fp = fopen('file.csv ', 'w '); foreach ($ arr as $ row) {// format a row as CSV and write the file pointer fputcsv ($ fp, $ row);} fclose ($ fp ); unset ($ arr); // import CSV table: CSV to array $ fp = fopen('file.csv ', 'R'); while ($ row = fgetcsv ($ fp ))! = FALSE) {// read a row from the file pointer and parse the CSV $ arr [] = $ row;} fclose ($ fp); var_export ($ arr );
Save as an independent File
Download. php:
<? Php $ list = array ('aaa, bbb, ccc, ddddd', '000000', '"aaa", "bbb"'); session_start (); $ _ SESSION ['outputarray'] = $ list;?> <A href = "test. php" target = "_ blank"> download a csv file </a>
Test. php:
<?phpsession_start();$outputArray=$_SESSION['outputArray'];header('Content-Type: application/csv');header('Content-Disposition: attachment;filename="sales.csv"');$output=fopen('php://output','w') or die("can not open");foreach ($outputArray as $line) { fputcsv($output, split(',', $line));}fclose($output) or die("can not close");?>
Automatically save the csv file to the specified location
<?php$list = array ( 'aaa,bbb,ccc,dddd', '123,456,789', '"aaa","bbb"');$fp = fopen('file.csv', 'w');foreach ($list as $line) { fputcsv($fp, split(',', $line));}fclose($fp);?>