doushe7934 2014-04-24 02:31
浏览 58
已采纳

在php中创建一个CSV文件[关闭]

I want to create a new CSV File with some values in it and store under my upload directory. Can anyone guide me how I can create a CSV and what code to be written in PHP. Also I want the CSV file with name of input parameter of the form and with current date.

Example: Test_24-04-2014.csv.

Also It will great if you can advise me how I can define a Column Header.

Example:

----------------------------------------
Sr. No           Name              Invt.
----------------------------------------
  • 写回答

2条回答 默认 最新

  • dqx24298 2014-04-24 03:35
    关注

    Consider this as an example, first off, of course you need a form:

    Sample Form:

    <!-- HTML -->
    <form method="POST" action="processes_the_form.php">
        Sr No.: <input type="text" name="srno" /><br/>
        Name: <input type="text" name="name" /><br/>
        Invt.: <input type="text" name="invt" /><br/>
        <input type="submit" name="submit" value="Add to CSV" />
    </form>
    

    Then process it in PHP:

    <?php
    // set delimitter (tab or comma)
    $delimitter = chr(9); // this is a tab
    $newline = "
    "; // CRLF or whatever you want
    
    // handle form submit
    if(isset($_POST['submit'])) {
        // gather values
        $srno = $_POST['srno'];
        $name = $_POST['name'];
        $invt = $_POST['invt'];
    
        // check for the csv file
        $directory = ''; // sample: path/to/csv/
        $prefix = 'Test_';
        $date = date('d-m-Y');
        $file_path = $directory . $prefix . $date . '.csv';
    
        // initial creation
        if(!file_exists($file_path)) {
            $file = fopen($file_path, 'w');
            // add the headers
            $headers = array('SrNo', 'Name', 'Invt');
            fputcsv($file, $headers, $delimitter);
            fclose($file);
        }
    
        $formatted_data = array($srno, $name, $invt);
        // put them inside the file and append on end
        $file = fopen($file_path, 'a');
        fputcsv($file, $formatted_data, $delimitter);
        fclose($file);
    }
    
    ?>
    

    Note: You may need to set your permissions to that PHP to create/write on that particular path

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧