本文目錄一覽:
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中的三行數據
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154249.html