Jump to: navigation, search

Php fputcsv

From w3cyberlearnings

Contents

PHP function fputcsv

This function formats line as CVS and write it to a file.

Syntax fputcsv

  • file is the file handle and created by fopne().
  • fields is the content to write to the file as a cVS, and it is an array
  • separator is the field separator, and its default is a comma (,)
  • enclosure is the field enclosure (one character only)
fputcsv(file, fields, separator, enclosure);

Note

Check out fgetcsv() function.

Example 1

<?php

$list = array(
	 array('bob', 'id2', '24', 'mit'),
	 array('john', 'id3', '25', 'mit'),
	 array('lov', 'id1', '23', 'mit')
);

$fh = fopen('file.csv', 'w');

foreach ($list as $fields) {
	fputcsv($fh, $fields);
}

fclose($fh);
?>

Output

file.csv content

bob,id2,24,mit
john,id3,25,mit
lov,id1,23,mit

Example 2

<?php

$list = array(
	 array('bob', 'id2', '24', 'mit'),
	 array('john', 'id3', '25', 'mit'),
	 array('lov', 'id1', '23 34', 'mit')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
	fputcsv($fp, $fields,':','%');
}

fclose($fp);
?>

Output

bob:id2:24:mit
john:id3:25:mit
lov:id1:%23 34%:mit

Example 3


$result = mysql_query('SELECT student_id, name, age, class FROM student');
if (!$result) die('Couldn\'t fetch records');

$fh = fopen('testCSV.csv', 'w');
if ($fh && $result) {
    while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
        fputcsv($fh, array_values($row));
    }
    die;
}
fclose($fh);

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