Jump to: navigation, search

Php fgetcsv

From w3cyberlearnings

Contents

PHP function fgetcsv

This function checks the file handler for CSV fields and it returns array.

Syntax fgetcsv

  • file: file handler
  • length (optional): maximum length of a line and it must greater than the longest line. Set to 0 for unlimited line.
  • separator (optional): field separator. (Default is comma ,).
  • enclosure (optional): field enclosure. (Default is double quote).
fgetcsv(file, length, separator, enclosure);

File Content (myfile.txt)

  • CSV File
name,country,tel
paul,usa,311-888-8888
kini,india,889-444-4444
yilig,china,888-333-3333
kiko,japan,893-333-33334

Example 1

<?php

$file = fopen("myfile.txt", "r");
print_r(fgetcsv($file));
fclose($file);
?>

Output

Array
(
    [0] => name
    [1] => country
    [2] => tel
)

Example 2

<?php

$file = fopen("myfile.txt", "r");
while (!feof($file)) {
	print_r(fgetcsv($file));
}
fclose($file);
?>

Output


Array
(
    [0] => name
    [1] => country
    [2] => tel
)
Array
(
    [0] => paul
    [1] => usa
    [2] => 311-888-8888
)
Array
(
    [0] => kini
    [1] => india
    [2] => 889-444-4444
)
Array
(
    [0] => yilig
    [1] => china
    [2] => 888-333-3333
)
Array
(
    [0] => kiko
    [1] => japan
    [2] => 893-333-33334
)

File Content (myfile2.txt)

name:country:tel
paul:usa:311-888-8888
kini:india:889-444-4444
yilig:china:888-333-3333
kiko:japan:893-333-33334

Example 3

<?php

$file = fopen("myfile2.txt", "r");
while (!feof($file)) {
	print_r(fgetcsv($file,0,':'));
}
fclose($file);
?>

Output


Array
(
    [0] => name
    [1] => country
    [2] => tel
)
Array
(
    [0] => paul
    [1] => usa
    [2] => 311-888-8888
)
Array
(
    [0] => kini
    [1] => india
    [2] => 889-444-4444
)
Array
(
    [0] => yilig
    [1] => china
    [2] => 888-333-3333
)
Array
(
    [0] => kiko
    [1] => japan
    [2] => 893-333-33334
)

Related Links


basename-- chgrp-- chmod-- chown-- clearstatcache-- copy-- delete-- dirname-- disk_free_space-- disk_total_space-- diskfreespace-- fclose-- feof-- fflush-- fgetc-- fgetcsv-- fgets-- fgetss-- file_exists-- file_get_contents-- file_put_contents- file-- fileatime-- filectime-- filegroup-- fileinode-- filemtime-- fileowner-- fileperms-- filesize-- filetype-- flock-- fnmatch-- fopen-- fpassthru-- fputcsv-- fputs-- fread-- fscanf-- fseek-- fstat-- ftell-- ftruncate-- fwrite-- glob-- is_dir-- is_executable-- is_file-- is_link-- is_readable-- is_uploaded_file-- is_writable-- is_writeable-- lchgrp-- lchown-- link-- linkinfo-- lstat-- mkdir-- move_uploaded_file-- parse_ini_file-- parse_ini_string-- pathinfo-- pclose-- popen-- readfile-- readlink-- realpath_cache_get-- realpath_cache_size-- realpath-- rename-- rewind-- rmdir-- set_file_buffer-- stat-- symlink-- tempnam-- tmpfile-- touch-- umask-- unlink--

Navigation
Web
SQL
MISC
References