在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.
----------------------------------------
我想创建一个新的 CSV文件 em>,其中包含一些值并存储在我的下面 上传目录。 任何人都可以指导我如何创建CSV以及用PHP编写的代码。 另外,我想要CSV文件,其中包含表单输入参数的名称和当前日期。 p>
示例: 如果你能告诉我怎么样我也会很棒 可以定义列标题。 p>
示例: p>
Test_24-04-2014.csv code>。 p>
----------------------- ----------------- \ NSR。 No Name Invt。
----------------------------------------
代码> pre>
div>
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
To define column headers in CSV, you imply add one line at the beginning containing your columns headers. For example:
"First name", "Family name", "Age"
"John", "Doe", "21"
"Jack", "Smith, "34"
To generate CSV files from PHP, you can use the fputcsv
function