Writing CSV6:04 with Alena Holligan
In this video we take data from a form to added another person to our recommended list. We'll be appending our file to add an additional line to our CSV file.
If you are not able to write to the file, make sure the file permissions are set
- Open the console: View > Show Console
- Run: chmod 777 data/csv/people.csv
It's usually a good idea not to rely on 3rd parties to store important data for you like images. They are not required to keep that information up just so you site works properly. If YOU are purposefully storing files with a 3rd party like a CDN (content delivery network), that is perfectly valid. I have downloaded the Twitter images into the project "img" folder for the download and workspaces, I also changed the links in the CSV to point to the local copies of the files. If you want to add your own people and not rely on a 3rd party to host the image, make sure you download those images locally as well.
Properly Formatted CSV
A properly formatted CSV file will end with an empty line, but you shouldn't count on that.
fputcsv – formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle. Only the first two parameters are required.
handle The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
fields An array of values.
delimiter The optional delimiter parameter sets the field delimiter (one character only). DEFAULT is comma. If you wish to save as tab delimited, you would use
enclosure The optional enclosure parameter sets the field enclosure (one character only). Treats the characters within the enclosed characters as a single item string. DEFAULT double quote. To use a single quote
escape_char The optional escape_char parameter sets the escape character (one character only).
$array = [ 'one 1', 'two ', 'three, "3"' ]; $fh = fopen('test.txt', 'w'); fputcsv($fh, $array); fputcsv($fh, $array, "\t", "'", "\\"); fclose($fh); //results //Line 1: "one 1","two's ","three, ""3""" //Line 2: 'one 1' 'two''s ' 'three, "3"'
fseek – Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence.
fopen – binds a named resource, specified by filename, to a stream.
fgets – Gets a line from file pointer.
fputs – Alias of fwrite(), which writes the contents of string to the file stream pointed to by handle.
fclose – closes the file pointed to by handle.
You need to sign up for Treehouse in order to download course files.Sign up