Fetching data from a CSV file using PHP
By admin
To open a CSV file, start by opening the file by using PHP function fopen.
<pre class="lang:php decode:true ">$filePointer = fopen(CSV_FILE_PATH, "r"); // Modes: 'r' for read-only, 'w' for write-only, 'a' for append
After opening the file (creating file pointer), cycle through the content using fgetcsv function. This function reads the file line by line and parse it based on fields in CSV.
<pre class="lang:php decode:true ">while (($list = fgetcsv($filePointer)) !== FALSE) // looping through each line
Note: Second parameter of fgetcsv must be set to the biggest line in the CSV file in character. By default its value is zero but it would be faster if you know the longest line in your CSV file and specify it.
Code block:
<pre class="lang:php decode:true ">$headerFlag = 0;
$buffer = 10000; // number of character of the longest line in CSV file
while (($list = fgetcsv($filePointer, $buffer)) !== FALSE) { // You can mention delimiter here if your CSV doesn't use comma
// Skip CSV header
if ($headerFlag == 0) {
$headerFlag = 1;
continue;
}
list($col1, $col2, $col3, $col4, $col5) = $list;
// .... Use $col values
}