Home > php教程 > php手册 > php array数组生成csv文件

php array数组生成csv文件

WBOY
Release: 2016-05-25 16:38:08
Original
1001 people have browsed it

在php中生成csv文件的方法很是简单,这里我来介绍一下自己用到的一个实例,把数组直接转换成csv文件输出,有需要了解的朋友可参考,代码如下:

<?php  
$data = array(  
    array( &#39;row_1_col_1&#39;, &#39;row_1_col_2&#39;, &#39;row_1_col_3&#39; ),  
    array( &#39;row_2_col_1&#39;, &#39;row_2_col_2&#39;, &#39;row_2_col_3&#39; ),  
    array( &#39;row_3_col_1&#39;, &#39;row_3_col_2&#39;, &#39;row_3_col_3&#39; ),  
);  
$filename = "example";  
header("Content-type: text/csv");  
header("Content-Disposition: attachment; filename={$filename}.csv");  
header("Pragma: no-cache");  
header("Expires: 0"); 
outputCSV($data);
Copy after login


function outputCSV($data) {  
    $outputBuffer = fopen("php://output", &#39;w&#39;);  
    foreach($data as $val) {  
    foreach ($val as $key => $val2) {  
     $val[$key] = iconv(&#39;utf-8&#39;, &#39;gbk&#39;, $val2);// CSV的Excel支持GBK编码,一定要转换,否则乱码  
     }  
        fputcsv($outputBuffer, $val);  
    }  
    fclose($outputBuffer);  
}
Copy after login

例2,看一个读取csv文件的实例,读取cvs,使用fgetcsv()文件指针中读入一行并解析 CSV 字段,比如说我要读取如下csv文件,代码如下:

<?php 
/** by www.phprm.com */ 
$row = 1; 
$handle = fopen("file.csv","r"); 
//fgetcsv() 解析读入的行并找出 CSV格式的字段然后返回一个包含这些字段的数组。  
while ($data = fgetcsv($handle, 1000, ",")) { 
$num = count($data); 
echo "<p> $num fields in line $row: <br>\n"; 
$row++; 
for ($c=0; $c < $num; $c++) { 
    //注意中文乱码问题 
    $data[$c]=iconv("gbk", "utf-8//IGNORE",$data[$c]);   
        echo $data[$c] . "<br>\n"; 
    } 
} 
fclose($handle);
Copy after login


文章地址:

转载随意^^请带上本文地址!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template