我一直在网上搜索关于使用PHP将数据从textarea导出到CSV ...
我想让我的页面上的按钮生成CSV文件,并在按下时提供下载。
我所能找到的只是从html表或mysql导出而我不需要...
基本上textarea包含一些数据,一旦按下按钮,我希望能够将该数据下载为CSV文件......
以下是我尝试自定义的课程:
<?php
class textarea_2_csv{
var $arrLines;
var $data;
var $divider;
function __construct($postedData){
$this->arrLines = explode("\r\n",$postedData['xls']);
$this->data = NULL;
}
// process the posted data
function set_data(){
if(is_array($this->arrLines)){
if($this->divider == NULL) $this->set_divider(); // default divider setting if no other option is passed
foreach($this->arrLines as $key=>$line){
// if more than 1 field
if(strpos($line, chr(9)) !== FALSE){
$arrFields = explode(chr(9),$line);
foreach($arrFields as $c=>$val){
$this->data .= $val.$this->divider;
}
$this->data = trim($this->data,$this->divider);
$this->data .= "\r\n";
}
// if only 1 field
else{
$this->data .= $line."\r\n";
}
}
}
}
// saves the data as file or returns it back
function save_data($write = false){
$this->set_data();
if(!$write == false){
// write file (.txt if divider is tab)
($this->divider == chr(9)) ? $ext = '.txt' : $ext = '.csv';
if(file_put_contents($write.$ext, $this->data)) echo('<h3>Data saved in file: '.$write.$ext.'</h3>');
return(NULL);
}
else{
// return de data
return($this->data);
}
}
// set the divider as default to a comma
function set_divider($opt=','){
$this->divider = $opt;
}
}
以下是实际页面:
<?php
require_once('class.textarea2csv.php');
/*
* 1) initiate the class passing the $_POST data
* 2) optional: set a different divider than comma (default) with function set_divider(';') or set_divider(chr(9)); options are: ; and tab
* 3) call the function save_data() without parameter to get the data returned OR call the function save_data('filename') with a parameter to save the data with the given filename
*/
if(isset($_POST['xls']) && trim($_POST['xls']) != ''){
$csv = new textarea_2_csv($_POST);
// possibility to set the divider to another format
// $xls->set_divider(';');
// $xls->set_divider(chr(9));
// process data and save it with filename output
$data = $csv->save_data('output');
}
?>
<html>
<h2>Example of class "Textarea 2 csv"</h2>
<p>Copy the the content of an excel sheet, paste it in the textarea and click on "Send".</p>
<form method="post">
<p><textarea name="xls" style="width: 800px; height: 400px"></textarea></p>
<p><input type="submit" value="Send" /></p>
</form>
</html>
我无法按照我的意愿自定义它......
再一次,textarea已经填充了一些数据,当有人点击按钮时,他/她应该将这些数据导出为CSV文件。
谢谢。
答案 0 :(得分:0)
您可以尝试:
if($bdd = mysqli_connect('localhost', 'root', '', 'checkport'))
{
if(isset($_POST['sub']))
{
$drp = "delete from listeadresse";
mysqli_query($bdd, $drp);
$filename=$_FILES["file"]["tmp_name"];
$file = fOpen($filename, "r");
$count=0;
while(($emapdata = fgetcsv($file, 100, ";")) !== FALSE )
{