21st Jan 2021
PHP [Versions: 4, 5, 7, 8]
Parsing lines from a read file for fields/columns in CSV format which returns an array containing the fields read.
- 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.
- 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()
<?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 (  => First Name  => Last Name  => Date of Birth )
Used In Projects
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.