15 1 0 4000 1 https://codeblock.co.za 300 true 0
theme-sticky-logo-alt

fgetcsv()

0 Comments

Programming Language

PHP [Versions: 4, 5, 7, 8]

Syntax

Typical Usage

Parsing lines from a read file for fields/columns in CSV format which returns an array containing the fields read.

Accepted Parameters

  • file(resource) (Required): A valid file successfully opened by fopen(), popen(), or fsockopen().
  • length (integer) (Optional) (Default = 0): The length be greater than the longest line (in characters) in the CSV file. If not, the line is split in chunks of the characters specified in length, unless the split would occur inside an enclosure.
    When setting length to 0, a maximum length is not limited
  • delimiter (string) (Optional) (Default = ‘,’): The file’s delimiter, usually a comma, semicolon or tab. Only one character is permitted.
  • enclosure (string) (Optional) (Default = empty): sets the field enclosure character.
  • escape (string) (Optional) (Default =’\\’): sets the escape character  

Return Value(s)

If the file is valid, returns an array containing the fields / columns read. Returns null if the file is invalid and false on other errors.

Notes

  • A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
  • fgetcsv() will move the pointer to the next line once complete. This means if you call it it again, it will start running from the next row. To go back to the previous row use rewind().

Examples of fgetcsv()

Example 1

<?php
$uploaded_file =$_FILES['uploaded-csv']

$my_file= fopen($uploaded_file['tmp_name'], 'r');

$headers = fgetcsv($my_file, 0, ',');
return $headers;

The above will output will be an array of each of the CSV columns in an array. For example:

Array
  (
      [0] => First Name
      [1] => Last Name
      [2] => Date of Birth
  )

Was This Helpful?

Previous Post
fopen()
Next Post
array_map()

0 Comments

Leave a Reply