댓글 검색 목록

[php] PHP MySQL로 내보내기 CSV를 가져 오는 3 단계

페이지 정보

작성자 운영자 작성일 20-04-17 15:04 조회 1,049 댓글 0

가져오기 및 내보내기 


PHP 및 MySQL로 CSV를 가져오고 내보내는 방법에 대한 자습서를 시작합니다. 따라서 목록을 내 보내야 하는 웹 사이트나 프로젝트가 있거나 판매 데이터 및 물건의 업로드를 처리해야 할 수도 있습니다. 두려워하지 마십시오 –이 안내서에서 단계별로 정확하게 살펴 보겠습니다. 알아 보려면 계속 읽으십시오!


ⓘ이 튜토리얼을 시작할 때 모든 예제 소스 코드가 포함 된 zip 파일을 포함 시켰으므로 모든 내용을 복사하여 붙여 넣을 필요가 없습니다.


예제 코드 다운로드 


먼저 약속 한대로 소스 코드에 대한 다운로드 링크가 있습니다.


소스 코드 다운로드 


예제 소스 코드를 다운로드하려면 여기를 클릭하십시오. MIT 라이센스에 따라 릴리스 했으므로 코드 위에 빌드하거나 자신의 프로젝트에서 자유롭게 사용할 수 있습니다.


폴더 


다음은 zip 파일에서 폴더를 구성하는 방법에 대한 간략한 소개입니다.


  • lib : 모든 PHP 라이브러리 파일을 저장하는 곳.
  • SQL : 데이터베이스를 빌드하는 데 필요한 모든 SQL 파일 모두 가져온 후에 안전하게 삭제할 수 있습니다.


빠른 시작 


  • 폴더에 다운로드하여 압축을 풉니다.
  • 데이터베이스를 작성하고 sql 폴더의 모든 파일을 가져 오십시오.
  • lib / 2a-config.php의 데이터베이스 설정을 원하는 대로 변경하십시오.
  • 가져 오기 데모 용 브라우저에서 3a-import.php를 실행하고 내보내기 데모 용 3b-export.php를 실행하십시오.


개요 


공식적으로 코드를 작성하기 전에 몇 가지 기본 사항과 이 예제의 개요부터 시작하겠습니다. 따라서 예상 할 사항을 알 수 있습니다.


예 시나리오 


이 가이드에서는 매우 간단한 사용자 데이터베이스를 예로 사용합니다. CSV 파일에서 사용자를 가져 오는 방법과 users 테이블에서 사용자를 내보내는 방법에 대해 작업합니다.


CSV 란 무엇입니까? 


CSV는 쉼표로 구분 된 값을 나타내며 일반 용어로 "스프레드시트"라고 부를 수 있습니다. 그러나 실제로 CSV 파일은 다음과 같은 일반 텍스트 파일입니다.


hello,world,foo,bar goodbye,world,doge,cate 


CSV 파일의 모든 쉼표는 열을 나타내며 모든 줄 바꿈은 "스프레드 시트"의 행입니다. 그러나 "레트 스프레드 시트"와 달리 CSV 파일은 열 너비 나 텍스트 스타일을 저장하지 않습니다. 따라서 파일을 올바로 저장 한 후에도 "굵게"및 열 너비 조정이 사라지는 것을 보고 놀라지 마십시오.


데이터베이스 및 샘플 


이 프로젝트의 기초부터 시작하겠습니다 – 사용자 데이터베이스 테이블과 더미 사용자 CSV 파일을 생성합니다.


DUMMY 사용자 테이블 


CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `user_email` varchar(255) NOT NULL, `user_name` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `user_email` (`user_email`), ADD KEY `user_name` (`user_name`); ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT; COMMIT; 


FieldDescription
user_idThe user ID. Primary key, auto-increment.
user_emailThe users’ email.
user_nameThe users’ name.

샘플 CSV 파일 


jane@doe.com,Jane Doe joe@doe.com,Joe Doe john@doe.com,John Doe julie@doe.com,Julie Doe johan@doe.com,Johan Doe joanne@doe.com,Joanne Doe juliet@doe.com,Juliet Doe june@doe.com,June Doe juan@doe.com,Juan Doe jamir@doe.com,Jamir Doe jaden@doe.com,Jaden Doe james@doe.com,James Doe janus@doe.com,Janus Doe jason@doe.com,Jason Doe jay@doe.com,Jay Doe jeff@doe.com,Jeff Doe jenn@doe.com,Jenn Doe joah@doe.com,Joah Doe joyce@doe.com,Joyce Doe joy@doe.com,Joy Doe juke@doe.com,Juke Doe johnnie@doe.com,Johnnie Doe jim@doe.com,Jim Doe jess@doe.com,Jess Doe jabril@doe.com,Jabril Doe 


라이브러리 파일 


이제 기초가 설정되었으므로 가져 오기 / 내보내기를 처리 할 PHP 라이브러리 파일을 작성해 보겠습니다.


구성 파일 


<?php // MUTE NOTICES error_reporting(E_ALL & ~E_NOTICE); // DATABASE SETTINGS - CHANGE THESE TO YOUR OWN define('DB_HOST', 'localhost'); define('DB_NAME', 'test'); define('DB_CHARSET', 'utf8'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); // AUTO PATH define('PATH_LIB', __DIR__ . DIRECTORY_SEPARATOR); ?> 


먼저, 모든 데이터베이스 설정과 내용을 안전하게 저장하기 위해 구성 파일을 작성하십시오. –이 설정을 자신의 것으로 변경하십시오.


사용자 라이브러리 


<?php class Users { /* [DATABASE HELPER FUNCTIONS] */ protected $pdo = null; protected $stmt = null; public $error = ""; public $lastID = null; function __construct() { // __construct() : connect to the database // PARAM : DB_HOST, DB_CHARSET, DB_NAME, DB_USER, DB_PASSWORD // ATTEMPT CONNECT try { $str = "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET; if (defined('DB_NAME')) { $str .= ";dbname=" . DB_NAME; } $this->pdo = new PDO( $str, DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false ] ); return true; } // ERROR - DO SOMETHING HERE // THROW ERROR MESSAGE OR SOMETHING catch (Exception $ex) { print_r($ex); die(); } } function __destruct() { // __destruct() : close connection when done if ($this->stmt !== null) { $this->stmt = null; } if ($this->pdo !== null) { $this->pdo = null; } } function exec($sql, $data=null) { // exec() : run insert, replace, update, delete query // PARAM $sql : SQL query // $data : array of data try { $this->stmt = $this->pdo->prepare($sql); $this->stmt->execute($data); $this->lastID = $this->pdo->lastInsertId(); } catch (Exception $ex) { $this->error = $ex; return false; } $this->stmt = null; return true; } function fetch($sql, $cond=null, $key=null, $value=null) { // fetch() : perform select query // PARAM $sql : SQL query // $cond : array of conditions // $key : sort in this $key=>data order, optional // $value : $key must be provided, sort in $key=>$value order $result = false; try { $this->stmt = $this->pdo->prepare($sql); $this->stmt->execute($cond); if (isset($key)) { $result = array(); if (isset($value)) { while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) { $result[$row[$key]] = $row[$value]; } } else { while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) { $result[$row[$key]] = $row; } } } else { $result = $this->stmt->fetchAll(); } } catch (Exception $ex) { $this->error = $ex; return false; } $this->stmt = null; return $result; } /* [USERS FUNCTIONS] */ function import () { /* (1) CHECK FILE TYPE */ if (strtoupper(pathinfo($_FILES['file-upload']['name'], PATHINFO_EXTENSION)) != "CSV") { $this->error = "Invalid file type - only CSV files are allowed"; return false; } /* (2) READ UPLOADED FILE + IMPORT TO DATABASE */ // !! IMPORTANT - Do not try to read the entire file into a string // !! That will kill the server on insane large uploads // !! Read line-by-line instead $handle = fopen($_FILES["file-upload"]["tmp_name"], "r"); if ($handle) { while (($line = fgetcsv($handle)) !== false) { // Use "REPLACE INTO" if you want to override the existing entries instead $sql = "INSERT INTO `users` (`user_name`, `user_email`) VALUES (?,?)"; $data = [$line[0], $line[1]]; $pass = $this->exec($sql, $data); // Remove these lines if you want the import operation to be "silent" print_r($line); echo "<br>"; echo $pass ? "OK" : $this->error; echo "<br>"; } fclose($handle); return true; } else { $this->error = "Error reading uploaded file!"; return false; } } function importAlt () { /* THIS IS AN ALTERNATIVE VERSION OF IMPORT * Bad idea to run a single INSERT query on every line read. * Can potentially run a few thousand times on large file imports. * This version will "gather" the data into temporary array, and only run the SQL on every 20 lines. * This should ease the round trip time, and speed up the entire import process. */ /* (1) CHECK FILE TYPE */ if (strtoupper(pathinfo($_FILES['file-upload']['name'], PATHINFO_EXTENSION)) != "CSV") { $this->error = "Invalid file type - only CSV files are allowed"; return false; } /* (2) READ UPLOADED FILE + IMPORT TO DATABASE */ $handle = fopen($_FILES["file-upload"]["tmp_name"], "r"); if ($handle) { $perrun = 20; $thisrun = 0; while (($line = fgetcsv($handle)) !== false) { if ($thisrun==0) { $sql = "INSERT INTO `users` (`user_name`, `user_email`) VALUES "; $data = []; } $sql .= "(?,?),"; $data[] = $line[0]; $data[] = $line[1]; $thisrun++; if ($thisrun==$perrun) { $sql = substr($sql, 0, -1) . ";"; $pass = $this->exec($sql, $data); $thisrun = 0; // Remove these lines if you want the import operation to be "silent" print_r($data); echo "<br>"; echo $pass ? "OK" : $this->error; echo "<br>"; } } if ($thisrun!=0) { $sql = substr($sql, 0, -1) . ";"; $pass = $this->exec($sql, $data); // Remove these lines if you want the import operation to be "silent" print_r($data); echo "<br>"; echo $pass ? "OK" : $this->error; } fclose($handle); return true; } else { $this->error = "Error reading uploaded file!"; return false; } } function export () { /* (1) CREATE NEW CSV FILE */ $handle = fopen("export.csv", "w"); if ($handle) { /* (2) GET ENTRIES FROM DATABASE */ $sql = "SELECT * FROM `users`"; $data = null; if ($_POST['search']!="") { $sql .= " WHERE `user_name` LIKE ? OR `user_email` LIKE ?"; $data = ["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]; } $this->stmt = $this->pdo->prepare($sql); $this->stmt->execute($data); /* (3) WRITE TO CSV FILE */ // !! IMPORTANT - Might crash server if fetch everything at one go // This will fetch from the database and write line-by-line while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) { fputcsv($handle, [$row['user_id'], $row['user_email'], $row['user_name']]); // Remove these lines if you want the import operation to be "silent" print_r($row); echo "<br>"; } /* (4) RETURN RESULTS */ fclose($handle); return true; } else { $this->error = "Failed to create export.csv"; return false; } } function exportDL () { /* (1) GET ENTRIES FROM DATABASE */ $sql = "SELECT * FROM `users`"; $data = null; if ($_POST['search']!="") { $sql .= " WHERE `user_name` LIKE ? OR `user_email` LIKE ?"; $data = ["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]; } $this->stmt = $this->pdo->prepare($sql); $this->stmt->execute($data); /* (2) SERVE HTTP HEADERS */ header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"export.csv\""); /* (3) SERVE DATA */ while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) { echo implode(",", [$row['user_id'], $row['user_email'], $row['user_name']]) . "\r\n"; } } } 


이 라이브러리는 처음에는 방대해 보이지만 두 섹션으로 나뉩니다.

  • 상위 절반은 SQL을 처리하는 데이터베이스 도우미 함수입니다.
  • 아래쪽 절반은 가져 오기 / 내보내기를 수행 할 실제 기능입니다.
Database Helper Functions
함수설명
__construct생성자 객체가 생성 될 때 데이터베이스에 자동으로 연결됩니다.
__destruct소멸자. 객체가 파괴 될 때 데이터베이스에서 자동으로 연결이 끊어집니다.
exec삽입, 바꾸기, 업데이트, 쿼리 삭제를 실행합니다.
fetch선택 쿼리를 실행합니다.
Import and Export Functions
함수설명
import이 함수는 임시 파일 업로드 $_FILES ['file-upload']에서 읽어서 데이터베이스에 삽입합니다.
importAlt가져 오기 함수의 대체 버전.
export이 함수는 데이터베이스에서 정보를 추출하여 서버의 CSV 파일에 저장합니다.
exportDL이 함수는 데이터베이스에서 정보를 추출하여 강제로 다운로드합니다.

가져 오기 예제에서는 점검이 수행되지 않습니다. – 사용자는 CSV 파일의 형식이 올바른지 확인해야 합니다. 예를 들어, 첫 번째 열은 이름이어야 하고 두 번째 열은 전자 우편이어야 합니다. 이 스크립트는 맹목적으로 가져 오지만 원하는 경우 직접 검사를 추가 할 수 있습니다.


가져오기 및 내보내기 페이지 


마지막으로 퍼즐의 마지막 부분은 라이브러리 기능을 사용할 가져 오기 및 내보내기 랜딩 페이지를 만드는 것입니다.


가져 오기 페이지 


<!DOCTYPE html> <html> <head> <title> CSV Import Example </title> </head> <body> <?php /* (A) SHOW UPLOAD FORM */ if (count($_FILES)==0) { ?> <form method="post" enctype="multipart/form-data"> <input type="file" name="file-upload" required> <input type="submit" value="Upload File" name="submit"> </form> <?php } /* (B) PROCESS IMPORT */ else { // If you are expecting a large upload, increase the timeout limit // Time in seconds. 0 is unlimited... But bad if this script hangs set_time_limit(0); require __DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "2a-config.php"; require PATH_LIB . "2b-lib-users.php"; $libUsr = new Users; $pass = $libUsr->import(); // Check out this alternate version too // $pass = $libUsr->importAlt(); echo $pass ? "Import OK" : $libUsr->error ; } ?> </body> </html> 


가져 오기 페이지는 매우 간단해야 하며 두 부분이 있습니다.


  • 상단은 매우 간단한 CSV 파일 업로드 양식일 뿐입니다.
  • 양식이 제출되면 하단 부분은 라이브러리를 사용하고 가져 오기 기능을 호출하여 업로드를 처리합니다.


내보내기 페이지 


<?php /* (A) PROCESS EXPORT IF FORM SUBMITTED */ require __DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "2a-config.php"; if (count($_POST)>0) { // If you are expecting a large export, increase the timeout limit // Time in seconds. 0 is unlimited... But bad if this script hangs set_time_limit(0); require PATH_LIB . "2b-lib-users.php"; $libUsr = new Users; // This version will write to a file on the server // $pass = $libUsr->export(); // echo $pass ? "Export OK" : $libUsr->error ; // This version will force a download $libUsr->exportDL(); } /* (B) SHOW EXPORT FORM */ else { ?> <!DOCTYPE html> <html> <head> <title> CSV Export Example </title> </head> <body> <form method="post"> <label for="search">Search for user name or email (optional)</label> <input type="text" name="search" id="search"> <input type="submit" value="Export CSV"> </form> </body> </html> <?php } ?> 


이 내보내기 페이지는 가져 오기 페이지와 거의 동일하며 2 개의 파트가 있습니다.


  • 상단 부분은 라이브러리를 사용하여 내보내기 요청을 처리하고 처리합니다.
  • 하단에는 HTML 내보내기 양식이 표시됩니다.

다운로드 및 요약 


이것으로 코드가 완성되었으며 여기에 유용한 몇 가지 추가 기능이 있습니다.


링크 및 참조 


요약 – 자신의 건물 


이제 모든 예제 스크립트를 다운로드 했으므로 다음 단계는 무엇입니까? 이것을 자신의 프로젝트에 구현하는 방법은 무엇입니까? 이 안내서의 3 단계를 기억하고 한 번에 하나씩 처리하면 제대로 수행됩니다.

  • The Database – 프로젝트 테이블을 아직 작성하지 않은 경우 작성하십시오.
  • Server-side Scripts – 프로젝트의 라이브러리 파일 및 가져 오기 / 내보내기 기능을 빌드하십시오. 자신에게 맞게 예제 라이브러리를 자유롭게 수정하십시오.
  • Client-side Scripts – 마지막으로 가져 오기 / 내보내기 HTML 페이지를 만듭니다.


댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.