本文目录一览:
PHP如何导出导入CSV文件?
你用过phpmyadmin了吗,那上面不是有这个功能吗,你自己去读源代码不就解决了吗
如何使用PHP导出csv和excel文件
把Excel文件导入mysql:
打开excel文件,可用phpExcel开源的类
或者:
先把excel文件另存为csv格式,最好是utf8编码。
fgetcsv() — 从文件指针中读入一行并解析 CSV 字段,返回数组
求源码!PHP导出数据到csv文件
?php
$DB_Server = "localhost";
$DB_Username = "root";
$DB_Password = "";
$DB_DBName = "DBName";
$DB_TBLName = "DB_TBLName";
$savename = date("YmjHis");
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect.");
mysql_query("Set Names 'gbk'");
$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Content-Type: application/$file_type;charset=gbk");
header("Content-Disposition: attachment; filename=".$savename.".$file_ending");
//header("Pragma: no-cache");
$now_date = date("Y-m-j H:i:s");
//$title = "数据库名:$DB_DBName,数据表:$DB_TBLName,备份日期:$now_date";
$sql = "Select * from $DB_TBLName";
$ALT_Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database");
$result = @mysql_query($sql,$Connect) or die(mysql_error());
//echo("$title\n");
$sep = "\t";
for ($i = 0; $i mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
$i = 0;
while($row = mysql_fetch_row($result)) {
$schema_insert = "";
for($j=0; $jmysql_num_fields($result);$j++) {
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
$i++;
}
return (true);
?
php如何读取CSV大文件并且将其导入数据库示例
思路:
读取csv文件,每读取一行数据,就插入数据库
示例
文件夹结构
/
file.csv //csv大文件,这里只模拟三行数据,不考虑运行效率(PS:csv文件格式很简单,文件一般较小,解析很快,运行效率的瓶颈主要在写入数据库操作)
index.php //php文件
file.csv
singi,20
lily,19
daming,23
index.php
/**
* 读取csv文件,每读取一行数据,就插入数据库
*/
//获取数据库实例
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'root';
$password = '';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e-getMessage();
}
//读取file.csv文件
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
//写入数据库
$sth = $db-prepare('insert into test set name=:name,age=:age');
$sth-bindParam(':name',$row[0],PDO::PARAM_STR,255);
$sth-bindParam(':age',$row[1],PDO::PARAM_INT);
$sth-execute();
}
fclose($handle);
}
数据表
CREATE TABLE `test` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL DEFAULT '' COLLATE 'utf8mb4_bin',
`age` INT(10) NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_bin'
ENGINE=InnoDB;
运行结束后,数据库中会插入csv中的三行数据