Home >Backend Development >PHP Tutorial >Two ways to read and write data with CSV files_PHP tutorial

Two ways to read and write data with CSV files_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:39:13838browse

Introduction: Sometimes we need to make statistics on the collected data and provide display and download on the page. In addition to traditional excel access, access to CSV files is also important. This article lists the detailed code for both operations.



Code:

$file = fopen('text.csv','r');
while ($data = fgetcsv($file)) { //Read one line of content in CSV each time
//print_r($data); //This is an array. To obtain each data, just access the array subscript
$goods_list[] = $data;
}
//print_r($goods_list);
echo $goods_list[0][1];
fclose($file);
?>



In actual work, it is often necessary to download some data from the website into a CSV file for later viewing.
Or you can use CSV to perform some batch upload work.
At this time we need to read and write CSV.
php CSV reading operation

Code:

$file = fopen('D:/file/file.csv','r');
while ($data = fgetcsv($file)) { //Read one line of content in CSV each time
print_r($data); //This is an array. To get each data, just access the array subscript
}
fclose($file);
?>


CSV writing operation
Code:

$fp = fopen('d:/file/file.csv', 'w');
fputcsv($fp,array('aaa','bbb','cccc')); // www.jbxue.com
fputcsv($fp,array('mmm','yyy','haha')); //fputcsv can be implemented by array loop
fclose($fp);
?>

fputcsv($fp,array('aaa','bbb','cccc'));

fputcsv($fp,array('mmm','yyy','haha')); //fputcsv can be implemented by array loop fclose($fp);

?>



Output CSV (download function)

Code:

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=test.csv");
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo "id,areaCode,areaName/n";
echo "1,cn,china/n";
echo "2,us,America/n";
?>

Output excel (download function)

header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=php100.xls");
echo "id,areaCode,areaName/n";
echo "1,cn,china/n";
echo "2,us,America/n";

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735047.htmlTechArticleIntroduction: Sometimes we need to make statistics on the collected data and provide display and download on the page. In addition to traditional excel access, access to CSV files is also important. This article lists...
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