Chúng ta cũng sẽ khám phá cách thực hiện thao tác phổ biến nhất như lọc, sắp xếp và chuyển đổi dữ liệu Cuối cùng nhưng không kém phần quan trọng, chúng ta sẽ tìm hiểu cách phân tích tệp CSV gồm 1 triệu dòng trong PHP một cách nhanh chóng và tiết kiệm bộ nhớ Tôi đã sử dụng PHP8 trong khi viết mã và kiểm tra các ví dụ - Các ví dụ với các hàm gốc tương thích với các phiên bản PHP rất cũ
- Các ví dụ sử dụng
// the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
6 yêu cầu phiên bản PHP7 ở mức tối thiểu - Toàn bộ có sẵn trong kho GitHub;
Ví dụ về tệp CSV của chúng tôiChúng tôi sẽ sử dụng tệp CSV chứa dữ liệu về phim trong hướng dẫn này Đây là một mẫu của tập dữ liệu này ở dạng văn bản thuần túy id,title,poster,overview,release_date,genres 181808,"Star Wars: The Last Jedi",https://.../mWII.jpg,"Rey develops her newly discovered abilities with the guidance of Luke Skywalker, [...]",1513123200,"Documentary" 383498,"Deadpool 2",https://.../3VAd.jpg,"Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad[...]",1526346000,"Action, Comedy, Adventure" 157336,"Interstellar",https://.../BvIx.jpg,"Interstellar chronicles the adventures of a group of explorers who make use of a [...]",1415145600,"Adventure, Drama, Science Fiction"
Thông thường, ở định dạng CSV - Dòng đầu tiên chứa tiêu đề
- Mỗi dòng sau là một hàng dữ liệu
- Dấu phẩy ngăn cách từng ô trong một hàng
- Một dấu ngoặc kép đóng gói các ô có chứa văn bản
Đôi khi, chúng ta có thể tìm các ký tự khác nhau để tách dữ liệu, đóng gói chuỗi hoặc thoát ký tự đặc biệt Hãy xem tệp mẫu của chúng tôi theo cách dạng bảng idtitleposteroverviewrelease_dategenres181808Star Wars. Jedi Cuối Cùnghttps. //. /mWII. jpgRey phát triển những khả năng mới khám phá của mình với sự hướng dẫn của Luke Skywalker, [. ]1513123200Phim tài liệu383498Deadpool 2https. //. /3VAd. jpg Lính đánh thuê khôn ngoan Deadpool chiến đấu với ác quỷ và mạnh mẽ Cable và những kẻ xấu khác[. ]1526346000Hành động, Hài, Phiêu lưu157336Liên saohttps. //. /BvIx. jpgInterstellar ghi lại những cuộc phiêu lưu của một nhóm các nhà thám hiểm sử dụng [. ]1415145600Phiêu lưu, Chính kịch, Khoa học viễn tưởngĐọc và ghi tệp CSV (Cách cũ)Đọc tệp CSV bằng fgetcsvCác bước để đọc tệp CSV bằng PHP với các hàm gốc - Mở tệp bằng
// the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
7 bằng chế độ đọc - Phân tích cú pháp các hàng CSV từ tệp bằng
// the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
8 - Đóng tệp bằng
// the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
9
$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
Nó tải từng hàng dưới dạng một mảng; // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
Trong một số trường hợp, chúng tôi muốn thao tác các hàng một cách độc lập, hãy chuyển đổi từng hàng CSV thành một mảng kết hợp // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
Bây giờ chúng ta có mỗi hàng dưới dạng một mảng kết hợp, với các tiêu đề là chỉ mục của mỗi mảng. Chúng ta có thể thao tác các hàng một cách độc lập như các đối tượng JSON đơn giản ________số 8_______
Viết tệp CSV bằng fputcsvCác bước để tạo tệp CSV trong PHP với các hàm gốc - Mở tệp bằng
// the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
7 bằng chế độ ghi - Viết mỗi mảng trong một hàng CSV với
// Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
1 - Đóng tệp bằng
// the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
9
$rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'w'); // open in write only mode (write at the start of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
Dấu phân cách mặc định là dấu phẩy, chúng ta có thể chỉ định các tham số khác nhau như // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
3, // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
4, // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
5 và // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
6 khi sử dụng hàm // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
8 và // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
1Nối các hàng mới vào tệp CSV bằng fputcsvHãy nối các hàng vào cuối tệp hiện có $rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'a'); // open in write only mode (with pointer at the end of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
Phần thiết yếu là hiểu tham số // Parse the rows $rows = []; $handle = fopen($path, "r"); while (($row = fgetcsv($handle)) !== false) { $rows[] = $row; } fclose($handle); // Remove the first one that contains headers $headers = array_shift($rows); // Combine the headers with each following row $array = []; foreach ($rows as $row) { $array[] = array_combine($headers, $row); } var_dump($array);
9 được sử dụng trong hàm // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
7array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
1 là chế độ chỉ đọcarray(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
2 là chế độ chỉ ghi, bắt đầu từ đầu tệp (xóa tệp hiện có)array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
3 là chế độ đọc/ghi, bắt đầu từ phần đầu của tệp (xóa tệp hiện có)array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
4 là chế độ chỉ ghi, bắt đầu từ cuối tệp (nối thêm nội dung vào cuối tệp)array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
5 là chế độ đọc/ghi, bắt đầu từ cuối tệp (nối thêm nội dung vào cuối tệp)
Sử dụng các chế độ array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
2, array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
3, array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
4, array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
5 sẽ tạo ra tệp CSV nếu nó chưa tồn tạiĐọc và ghi tệp CSV (Cách hiện đại)Cách tiếp cận đọc và viết trước đây hoàn toàn ổn, nhưng một số thư viện hiện đại có thể giúp cuộc sống của chúng ta dễ dàng hơn và mã của chúng ta dễ đọc hơn một chút Hướng dẫn này sử dụng thư viện // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
6 tuyệt vời, cung cấp API thao tác CSV rõ ràng và đơn giảnChúng ta cũng có thể lưu ý đến thư viện $rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'w'); // open in write only mode (write at the start of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
1 tuyệt vời, cũng rất mạnh, cung cấp hỗ trợ cho các định dạng khác và có thể được sử dụng để đọc và ghi các tệp Excel trong PHPCài đặt giải đấu/csvHãy cài đặt thư viện // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
6 bằng cách sử dụng trình quản lý gói của nhà soạn nhạccomposer require league/csv
Đọc tệp CSV bằng League\Csv\ReaderĐọc các hàng CSV từ một tệp bằng cách sử dụng ____12_______3 use League\Csv\Reader; $path = 'data/movies-100.csv'; $csv = Reader::createFromPath($path, 'r'); $csv->setHeaderOffset(0); // use the first line as headers for rows
$header = $csv->getHeader(); var_dump($header);
$rows = $csv->getRecords(); foreach ($rows as $row) { var_dump($row); }
Khi sử dụng cấu hình $rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'w'); // open in write only mode (write at the start of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
4, chúng ta có thể thấy một sự khác biệt nhỏ nhưng thú vị so với việc sử dụng hàm PHP gốc. Trình đọc // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
6 tải các hàng dưới dạng mảng kết hợp (đối tượng JSON). Nó làm cho thao tác dữ liệu dễ dàng hơn vì chúng ta có thể xử lý độc lập với từng hàngarray(6) { ["id"]=> string(3) "807" ["title"]=> string(5) "Se7en" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" ["overview"]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." ["release_date"]=> string(9) "811731600" ["genres"]=> string(24) "Crime, Mystery, Thriller" }
Viết tệp CSV bằng League\Csv\WriterViết các hàng CSV vào một tệp bằng cách sử dụng $rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'w'); // open in write only mode (write at the start of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
6$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
0
Đoạn mã này là một đoạn mã thú vị để xuất cơ sở dữ liệu của bạn dưới dạng tệp CSV; Hãy nhớ rằng khi chúng tôi sử dụng $rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'w'); // open in write only mode (write at the start of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
7 với chế độ array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
2, chúng tôi sẽ xóa toàn bộ nội dung tệp nếu nó đã tồn tạiNối các hàng mới vào tệp CSV bằng League\Csv\WriterĐôi khi, chúng ta cần nối thêm các dòng ở cuối tệp hiện có mà không xóa nội dung hiện tại của nó Trong trường hợp này, chúng tôi mở tệp bằng cách sử dụng giá trị array(100) { [0]=> array(6) { ["id"]=> string(6) "287947" ["title"]=> string(7) "Shazam!" ["poster"]=> string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg" ["overview"]=> string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word." ["release_date"]=> string(10) "1553299200" ["genres"]=> string(23) "Action, Comedy, Fantasy" } // more rows
5 cho tham số $rows = [ ['id', 'title', 'poster', 'overview', 'release_date', 'genres'], [181808, "Star Wars: The Last Jedi", "https://image.tmdb.org/t/p/w500/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", 1513123200, "Documentary"], [383498, "Deadpool 2", "https://image.tmdb.org/t/p/w500/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", 1526346000, "Action, Comedy, Adventure"], [157336, "Interstellar", "https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg", "Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.",1415145600,"Adventure, Drama, Science Fiction"] ]; $path = 'data/new-file.csv'; $fp = fopen($path, 'a'); // open in write only mode (with pointer at the end of the file) foreach ($rows as $row) { fputcsv($fp, $row); } fclose($fp);
0$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
1
Mẹo & thủ thuật nâng cao khi sử dụng League\CsvBây giờ, chúng ta sẽ khám phá các thao tác nâng cao nhưng thường được sử dụng trên CSV Đếm hàng CSV$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
2
Trả lại Tiêu đề CSV$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
3
$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
4
Tìm nạp một hàng CSV bằng cách sử dụng chỉ mục của nóChúng tôi tìm nạp hàng thứ 10 của tệp $path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
5
$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
6
Tìm nạp nhiều hàng CSV bằng cách sử dụng Offset và LimitChúng tôi lấy 3 hàng bắt đầu từ hàng thứ 10 $path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
7
Lọc hàng CSV dựa trên điều kiệnChúng tôi chỉ tìm nạp những phim có tiêu đề chứa "Deadpool" $path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
8
$path = 'data/movies-100.csv'; $handle = fopen($path, "r"); // open in readonly mode while (($row = fgetcsv($handle)) !== false) { var_dump($row); } fclose($handle);
9
Sắp xếp hàng CSV dựa trên điều kiệnChúng tôi tìm nạp năm bộ phim đầu tiên được sắp xếp theo tiêu đề theo thứ tự bảng chữ cái tăng dần // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
0
Chuyển đổi CSV sang JSONPhân tích cú pháp tệp CSV và chuyển đổi các hàng của nó thành chuỗi JSON là một thao tác khá đơn giản // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
1
Chuyển đổi JSON sang CSVChuyển đổi định dạng JSON thành tệp CSV yêu cầu nhiều công việc hơn một chút; // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
2
Nếu bạn muốn tìm hiểu thêm về thao tác tệp JSON, bạn có thể xem bài đăng chuyên dụng này về cách đọc và ghi tệp JSON bằng PHP Đọc tệp CSV lớn trong khi sử dụng bộ nhớ tối thiểuMẹo để phân tích các tệp CSV lớn bằng cách duy trì mức sử dụng bộ nhớ thấp là không bao giờ tải tất cả dữ liệu trong bộ nhớ May mắn thay, cả phương pháp đọc bản địa và // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
6 đều cho phép chúng tôi lặp lại và truyền phát nội dungHãy lấy một ví dụ về tệp chứa 1M dòng; // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
3
Hãy tải tất cả nội dung của nó // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
4
và đây là kết quả // the headers array(6) { [0]=> string(2) "id" [1]=> string(5) "title" [2]=> string(6) "poster" [3]=> string(8) "overview" [4]=> string(12) "release_date" [5]=> string(6) "genres" } // another row array(6) { [0]=> string(3) "807" [1]=> string(5) "Se7en" [2]=> string(63) "https://image.tmdb.org/t/p/w500/6yoghtyTpznpBik8EngEmJskVUO.jpg" [3]=> string(390) "Two homicide detectives are on a desperate hunt for a serial killer whose crimes are based on the 'seven deadly sins' in this dark and haunting film that takes viewers from the tortured remains of one victim to the next. The seasoned Det. Sommerset researches each sin in an effort to get inside the killer's mind, while his novice partner, Mills, scoffs at his efforts to unravel the case." [4]=> string(9) "811731600" [5]=> string(24) "Crime, Mystery, Thriller" }
5
Chúng tôi tải 1 triệu dòng CSV trong 26 giây bằng cách chỉ sử dụng 6 MB bộ nhớ. 🤯 Bằng cách truyền trực tuyến đúng cách đọc dữ liệu và xử lý bạn muốn áp dụng, bạn có thể giữ cho mức sử dụng bộ nhớ ở mức rất thấp Sử dụng phương pháp này, chúng tôi có thể viết trình phân tích cú pháp PHP CSV rất hiệu quả, đặc biệt có lợi khi nhập tệp CSV lớn vào cơ sở dữ liệu
Làm cách nào để thêm tiêu đề vào CSV bằng PHP?
Ví dụ cơ bản
. văn bản/csv; . tập tin đính kèm; . csv'); . //đầu ra', 'w'); . com', 'Kate Rose Morley']);
Làm cách nào để đọc cột tệp CSV một cách khôn ngoan trong PHP?
Bạn có thể mở tệp bằng cách sử dụng fopen() như bình thường, lấy từng dòng bằng cách sử dụng fgets() và sau đó chỉ cần ngắt tệp đó theo từng dấu phẩy like this:
Làm cách nào để lấy dữ liệu từ tệp CSV trong PHP?
Để hiển thị dữ liệu từ tệp CSV lên trình duyệt web, chúng ta sẽ sử dụng hàm fgetcsv(). . Giá trị được phân tách bằng dấu phẩy (CSV) là tệp văn bản chứa nội dung dữ liệu. . hàm fgetcsv(). Hàm fgetcsv() được sử dụng để phân tích cú pháp một dòng từ tệp đang mở, kiểm tra các trường CSV Các bước thực hiện tên tệp. mã số. php đầu ra
Làm cách nào để đọc tệp CSV trong từng dòng PHP?
Chúng tôi sẽ sử dụng fopen() và fgetcsv() để đọc nội dung của tệp CSV , sau đó chúng tôi sẽ chuyển đổi tệp đó . |