Maison >développement back-end >tutoriel php >用php导入导出csv文件

用php导入导出csv文件

WBOY
WBOYoriginal
2016-07-29 09:12:281048parcourir

用php导入导出csv文件

最近在做一些模块的时候,频繁导入导出csv文件,与excel相比他的处理更简单,文件体积更小,数据处理量大,而且很多语言都支持。

废话不多,上代码~

导入代码:

<code><span>meta</span><span>charset</span> = "<span>utf-8</span>"><span>form</span><span>method</span> = "<span>post</span>" <span>enctype</span> = "<span>multipart</span>/<span>form-data</span>" ><span>h3</span>><strong>上传文件</strong><span><span>h3</span>></span><span>input</span><span>type</span> = "<span>file</span>" <span>name</span> = "<span>file</span>"><span>button</span><span>type</span> = "<span>submit</span>" >提交<span><span>button</span>></span><span><span>form</span>></span><span><span><?php </span><span>$csv</span> = <span>$_FILES</span>[<span>'file'</span>];

    <span>$suffix</span> = array_pop(explode(<span>'.'</span>, <span>$csv</span>[<span>'name'</span>]));

    <span>//检查是否是csv文件</span><span>if</span>(<span>$suffix</span>  <span>'csv'</span>)
        <span>exit</span>(<span>'请上传csv文件'</span>);

    <span>$file</span> = fopen(<span>$csv</span>[<span>'tmp_name'</span>], <span>'r'</span>);

    <span>$lines</span> = <span>array</span>();

    <span>while</span>(<span>$data</span>  = fgetcsv(<span>$file</span>))
        <span>$lines</span>[] = <span>$data</span>;

    <span>echo</span><span>'<pre class="brush:php;toolbar:false">'
; print_r($lines); ?>

导出代码:

<code><span>meta</span><span>charset</span> = "<span>utf-8</span>" /><span>a</span><span>href</span> = "?<span>test</span>">点我下载CSV文件<span><span>a</span>></span><span><span><?php </span><span>if</span>(<span>isset</span>(<span>$_REQUEST</span>[<span>'test'</span>])){
    ob_end_clean();
    ob_start();

    <span>//第一行题头</span><span>echo</span><span>"题头1,题头2,题头3,题头4\n"</span>;
    <span>//第一行数值</span><span>echo</span><span>"数值1,数值2,数值3,数值4\n"</span>;

    <span>$content</span> = ob_get_contents();

    ob_end_clean();

    header(<span>'Content-Type: text/html;charset=gb2312'</span>);
    header(<span>'Content-Type: application/force-download'</span>);
    header(<span>'Content-Disposition: attachment; filename=test.csv'</span>);

    <span>echo</span> iconv(<span>'utf-8'</span>, <span>'gb2312'</span>, <span>$content</span>);
}
<span>?></span></span></span></code>

测试链接

上传功能测试链接

下载功能测试链接

以上~如果有不明白,可以留言

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了用php导入导出csv文件,包括了上传文件,导入导出方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn