PHP Fgetcsv (With Advanced Program Examples)

What is PHP fgetcsv?

The PHP fgetcsv() is a function used to read or parse the CSV (Comma/Character Separated Values) into the PHP program.

So whenever the programmers need to read or use a CSV file in their program, they will apply the fgetcsv() function.

In simple words, the fgetcsv() function does the required ability to the program whenever it needs to deal with CSV files.

What does PHP fgetcsv do?

The fgetcsv() method in PHP can examine a line from an open file for CSV fields and parse it.

So, the function stops going to a new line when either a certain length is reached or the end of the file is reached.

Furthermore, if the PHP fgetcsv() function works, it returns the CSV fields of the array.

If it fails or the file ends, it returns false.

Also, the fgetcsv() function is a bit like the fgets() function, except that it looks for CSV-formatted fields in the line it reads.

Syntax:

fgetcsv(file, length, separator, enclosure)

Parameter Values

ParameterDescription
fileThis parameter is required since it specifies the open file to return and parse from the CSV.
lengthThis parameter is only optional because you only need to specify it if you want to set the maximum length of the line. However, it must be greater than the longest line (by character) in the CSV file. Also, eliminating this parameter might cause the process to be slower, and for that reason, it has become required in other versions of PHP.
separatorThis parameter is also optional and it is applicable when specifying the field separator. Additionally, its default symbol is a comma (,).
enclosureThis parameter specifies the field enclosure of the character, and its default symbol is a double quote
("). It is also an optional parameter.
escapeThis parameter is also optional, with the default value of a double backslash symbol (\\). It specifies the escape character of the file.
PHP Parameter Table

Example Program fgetcsv in PHP

To see how the PHP fgetcsv() works, let us have some simple examples.

This example will read and display files from the CSV file present in the computer.

Take Note: When you try to perform this example, you must have a CSV file present on your computer with the name.csv.

This is a simple note to keep yourself from errors.

The file of the CSV that we will use is the sample.csv, and it contains some information such as follows:

  • Anne, Stone, 25, Negros, Philippines
  • Betty, Stone, 32, Cebu, Philippines

Example 1:

<?php
$file = fopen("sample.csv","r");
echo "<pre>";
print_r(fgetcsv($file));
echo "</pre>";
fclose($file);
?>

Output:

Array
(
    [0] => Anne
    [1] => Stone
    [2] => 25
    [3] => Negros
    [4] => Philippines
)

Program Explanation:

The example above simply gives you an idea of how the function will get the data from the CSV file.

It uses the fopen() and fclose() functions through the concept of fgetcsv() function to access the file.

Example 2:

<?php
$file = fopen("sample.csv","r");
while(! feof($file))
  {
  echo "<pre>";
  print_r(fgetcsv($file));
  echo "</pre>";
  }
fclose($file);
?>

Output:

Array
(
    [0] => Anne
    [1] => Stone
    [2] => 25
    [3] => Negros
    [4] => Philippines
)
Array
(
    [0] => Betty
    [1] => Stone
    [2] => 32
    [3] => Cebu
    [4] => Philippines
)

Program Explanation:

The same with the program explanation above, the second example also performs the same.

However, this example program gets all the possible data present in the file and shows it in the output.

Two Advanced Example Programs using fgetcsv in PHP

Example 1:

<?php
$CSVfp = fopen("sample.csv", "r");
if ($CSVfp !== FALSE) {
    ?>
    <div class="phppot-container">
        <table class="striped">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Age</th>
                    <th>Location</th>
                </tr>
            </thead>
<?php
    while (! feof($CSVfp)) {
        $data = fgetcsv($CSVfp, 1000, ",");
        if (! empty($data)) {
            ?>
            <tr class="data">
                <td><?php echo $data[0]; ?></td>
                <td><?php echo $data[1]; ?></td>
                <td><?php echo $data[2]; ?></td>
                <td><?php echo $data[3]; ?></td>

            </tr>
 <?php }
    }
    ?>
        </table>
    </div>
<?php
}
fclose($CSVfp);
?>

Output:

First Name	Last Name	Age	   Location
Anne	        Steel	        25	   Negros
Betty	        Stone	        32	   Cebu

Program Explanation:

To give you a heads-up, we use the sample.php file containing the following data:

First NameLast NameAgeProvinceCountry
Anne Steel25NegrosPhilippines
BettyStone32CebuPhilippines
Example of a CSV File

As you can see, the sample.csv file contains five columns and two rows of data.

However, the program only displays four columns of data, this is because the program specifies that the HTML table should only have four columns.

To perform the concept of transferring the data from the file to the table, we use the PHP fgetcsv() function as the value of $data.

This data is then assigned to fill the cells of the table by using the $data = fgetcsv($CSVfp, 1000, ","); line of code.

We also need to give a specific count of data to match the columns that we declared at the table head tag (<thead> </thead>).

The <tr></tr> tag or table rows should also correspond to the columns assigned in the table header.

This is to avoid encountering errors in implementing specifications.

Example 2:

<?php
$CSVfp = fopen("sample.csv", "r");
if ($CSVfp !== FALSE) {
    while (! feof($CSVfp)) {
        $data = fgetcsv($CSVfp, 1000, ",");
        if (! empty($data)) {
        	echo "<PRE>";
            echo "INSERT INTO sample (`first_name`, `last_name`, `age`, `place`, `country`) VALUES ('" . $data[0] . "', '" . $data[1] . "', '" . $data[2] . "', '" . $data[3] . "', '" . $data[4] . "');\r\n\n";
			echo "</PRE>";
        }
    }
}
fclose($CSVfp);
?>

Output:

INSERT INTO sample (`first_name`, `last_name`, `age`, `place`, `country`) VALUES ('Anne', 'Steel', '25', 'Negros', 'Philippines');

INSERT INTO sample (`first_name`, `last_name`, `age`, `place`, `country`) VALUES ('Betty', 'Stone', '32', 'Cebu', 'Philippines');

Program Explanation:

This second advanced example tries to show you how to use the PHP fgetcsv() function to insert the data from the CSV file into your database.

This example helps you with manipulating data through the use of queries.

As a result, the example shows lines of queries with the data from the file assigned to each of the given data slots.

Conclusion

In conclusion, the overall discussion of the PHP fgetcsv() function gives you the ability to access the data from a CSV file and display it in the output.

Learning the function can also enable you to manipulate the data in form of transferring or inserting them into a table or database.

All in all, this topic really will help you in dealing with CSV files by using the fgetcsv() function.

If you have any concerns or desire to discuss another topic, write it in the comments.

Leave a Comment