Buat csv dengan header php

Kami juga akan menjelajahi cara melakukan manipulasi yang paling umum seperti memfilter, menyortir, dan mengubah data

Last but not least, kita akan belajar cara mengurai file CSV 1 juta baris dalam PHP dengan cara yang cepat dan hemat memori

Saya menggunakan PHP8 saat membuat kode dan menguji contoh

  • Contoh dengan fungsi asli kompatibel dengan versi PHP yang sangat lama
  • Contoh menggunakan
    // 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 memerlukan versi PHP7 minimal
  • Semuanya tersedia di repositori GitHub;

Contoh File CSV Kami

Kami akan menggunakan file CSV yang berisi data tentang film dalam tutorial ini

Berikut adalah contoh kumpulan data ini dalam teks biasa

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"
_

Biasanya dalam format CSV

  1. Baris pertama berisi header
  2. Setiap baris berikutnya adalah baris data
  3. Koma memisahkan setiap sel dalam satu baris
  4. Kutipan ganda merangkum sel yang berisi teks

Terkadang, kita dapat menemukan karakter yang berbeda untuk memisahkan data, merangkum string, atau melepaskan karakter khusus

Mari kita lihat file contoh kita dengan cara tabel

idtitleposteroverviewrelease_dategenres181808Star Wars. Jedi Terakhirhttps. //. / mWII. jpgRey mengembangkan kemampuannya yang baru ditemukan dengan bimbingan Luke Skywalker, [. ]1513123200Dokumenter383498Deadpool 2https. //. /3VAd. jpg Deadpool tentara bayaran Wisecracking melawan Cable yang jahat dan kuat serta kejahatan lainnya[. ]1526346000Aksi, Komedi, Petualangan157336Antarbintanghttps. //. /BvIx. jpg Interstellar mengisahkan petualangan sekelompok penjelajah yang menggunakan [. ]1415145600Petualangan, Drama, Fiksi Ilmiah

Baca dan Tulis File CSV (Cara Kuno)

Baca File CSV Menggunakan fgetcsv

Langkah-langkah membaca file CSV di PHP dengan fungsi native

  1. Buka file dengan
    // 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 menggunakan mode baca
  2. Parsing baris CSV dari file dengan
    // 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
  3. Tutup file dengan ________0______9

$path = 'data/movies-100.csv';
$handle = fopen($path, "r"); // open in readonly mode
while (($row = fgetcsv($handle)) !== false) {
var_dump($row);
}
fclose($handle);

Itu memuat setiap baris sebagai larik;

// 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"
}

Dalam beberapa kasus, kami ingin memanipulasi baris secara independen, mari ubah setiap baris CSV menjadi array asosiatif

// 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);

Kami sekarang memiliki setiap baris sebagai array asosiatif, dengan header sebagai indeks dari setiap array. Kita dapat memanipulasi baris secara mandiri sebagai objek JSON sederhana

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
_

Tulis File CSV Menggunakan fputcsv

Langkah-langkah membuat file CSV di PHP dengan fungsi native

  1. Buka file dengan
    // 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 menggunakan mode tulis
  2. Tulis setiap larik dalam baris CSV dengan
    // 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
  3. Tutup file dengan ________0______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);

Pemisah default adalah koma, kita dapat menentukan parameter yang berbeda seperti

// 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 dan
// 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 saat menggunakan fungsi
// 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 dan
// 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

Tambahkan Baris Baru dalam File CSV Menggunakan fputcsv

Mari tambahkan baris di akhir file yang sudah ada

$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);

Bagian penting adalah memahami parameter

// 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 yang digunakan dalam fungsi
// 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

  • 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
    1 adalah mode read-only
  • 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 adalah mode hanya tulis, dimulai dari awal file (hapus file yang ada)
  • 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 adalah mode baca/tulis, dimulai dari awal file (hapus file yang ada)
  • 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 adalah mode tulis-saja, dimulai dari akhir file (tambahkan konten di akhir file)
  • 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 adalah mode baca/tulis, dimulai dari akhir file (tambahkan konten di akhir file)

Menggunakan mode

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 akan membuat file CSV jika belum ada

Baca dan Tulis File CSV (Cara Modern)

Pendekatan membaca dan menulis sebelumnya ini baik-baik saja, tetapi beberapa perpustakaan modern dapat membuat hidup kita lebih mudah dan kode kita sedikit lebih mudah dibaca

Tutorial ini menggunakan pustaka

// 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 yang luar biasa, yang menyediakan API manipulasi CSV yang bersih dan lugas

Kami juga dapat mencatat perpustakaan

$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 yang hebat, yang juga sangat kuat, menawarkan dukungan untuk format lain dan dapat digunakan untuk membaca dan menulis file Excel dalam PHP

Instal liga/csv

Mari instal pustaka

// 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 dengan menggunakan manajer paket komposer

composer require league/csv

Baca File CSV Menggunakan League\Csv\Reader

Baca baris CSV dari file menggunakan

$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);
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);
}

Saat menggunakan konfigurasi

$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, kita dapat melihat sedikit perbedaan yang menarik dibandingkan dengan penggunaan fungsi PHP asli. Pembaca
// 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 memuat baris sebagai array asosiatif (objek JSON). Itu membuat manipulasi data lebih mudah karena kita dapat menangani setiap baris secara mandiri

array(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"
}

Tulis File CSV Menggunakan League\Csv\Writer

Tulis baris CSV ke dalam file menggunakan

$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

Cuplikan kode ini menarik untuk mengekspor database Anda dalam file CSV;

Perlu diingat bahwa ketika kita menggunakan

$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 dengan mode
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, kita menghapus seluruh konten file jika sudah ada

Tambahkan Baris Baru dalam File CSV Menggunakan League\Csv\Writer

Terkadang, kita perlu menambahkan baris di akhir file yang sudah ada tanpa menghapus kontennya saat ini

Dalam hal ini, kami membuka file dengan menggunakan nilai

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 untuk parameter
$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

Tips & Trik Tingkat Lanjut Menggunakan League\Csv

Sekarang, kita akan menjelajahi operasi lanjutan namun umum digunakan di CSV

Hitung Baris 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

Kembalikan Header 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

Ambil Satu Baris CSV dengan Menggunakan Indeksnya

Kami mengambil baris ke-10 dari file tersebut

$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

Ambil Banyak Baris CSV dengan Menggunakan Offset dan Limit

Kami mengambil 3 baris mulai dari baris ke-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

Filter Baris CSV Berdasarkan Kondisi

Kami hanya mengambil film yang judulnya berisi "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

Urutkan Baris CSV Berdasarkan Kondisi

Kami mengambil lima film pertama yang diurutkan berdasarkan judul abjad yang berpengaruh

// 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

Konversikan CSV ke JSON

Mem-parsing file CSV dan mengonversi barisnya menjadi string JSON adalah operasi yang cukup mudah

// 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

Konversikan JSON ke CSV

Mengonversi format JSON ke file CSV membutuhkan lebih banyak pekerjaan;

// 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

Jika Anda ingin melangkah lebih jauh tentang manipulasi file JSON, Anda dapat melihat posting khusus ini tentang membaca dan menulis file JSON menggunakan PHP

Baca File CSV Besar Saat Menggunakan Memori Minimum

Trik untuk mem-parsing file CSV besar dengan menjaga penggunaan memori tetap rendah adalah dengan tidak pernah memuat semua data di memori

Untungnya, metode membaca asli dan

// 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 memungkinkan kita untuk mengulangi dan mengalirkan konten

Mari kita ambil contoh file yang berisi 1M baris;

// 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

Mari memuat semua kontennya

// 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

Dan inilah hasilnya

// 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

Kami memuat 1 juta baris CSV kami dalam 26 detik dengan hanya menggunakan memori 6MB. 🤯

Dengan mengalirkan dengan benar pembacaan data dan pemrosesan yang ingin Anda terapkan, Anda dapat menghemat penggunaan memori

Dengan menggunakan metode ini, kita dapat menulis parser PHP CSV yang sangat efisien yang sangat bermanfaat saat mengimpor file CSV besar ke database

Bagaimana cara menambahkan tajuk di csv menggunakan PHP?

Contoh dasar . teks/csv; . lampiran; . csv'); . //keluaran', 'w'); . com', 'Kate Rose Morley']);

Bagaimana cara menambahkan header ke file csv?

Jika file CSV Anda tidak memiliki header, Anda dapat menambahkannya hanya dengan membuat baris pertama baru di file teks dan mengetikkan header Anda.

Bagaimana cara membuat file csv dengan data itu di PHP?

Untuk mengonversi larik menjadi file CSV, kita dapat menggunakan fungsi fputcsv() . Fungsi fputcsv() digunakan untuk memformat baris sebagai file CSV (nilai yang dipisahkan koma) dan menulisnya ke file terbuka.

Bagaimana cara membaca header file CSV di PHP?

csv', 'r'); . file csv. $header = $csv->getHeader(); print_r($header); $records = $csv->getRecords(); print_r(iterator_to_array($records)); echo $csv->getContent(); We read the header and the data from the users. csv file.