Change a Value in a .CSV with PHP

After downloading a number of .CSV files from the National Archives, I found that I needed to add a colon to some of the fields.  In fields that listed times, they were formatted as "900" and I wanted them to be "9:00."  While there are a number of a ways to get this done, I figured I could do it manually in a few minutes with Excel.  After about a half hour, I realized I was wrong and set out to do the same thing with PHP.  The problem was that I had already added the colon to some of the fields in the .CSV.  This is what I needed to do:

  1. Use PHP to open the .CSV
  2.  Determine if there was already a colon in the field I needed to edit
  3. If there is a colon, write the entire line to a new .CSV file.  If there wasn't a colon, add one in the appropriate spot and write the altered line to the new .CSV file
//without this line, the script placed all the lines 
//of the original .CSV into a single array
//rather than creating a new array for each line
ini_set("auto_detect_line_endings", true);

$input_csv = fopen('original_file.csv','r');
$output_csv = fopen('output.csv', 'w');

while($csv_line = fgetcsv($input_csv)) {
//see if the desired value contains a colon
$raw_time = $csv_line[17];
$position = strpos($raw_time, ':');

if ($position === false) {
//if the value does not contain a colon, insert it
//and write it to the new file
$csv_line[17] = substr_replace($raw_time, ":", -2,0);
fputcsv($output_csv, $csv_line);
} else {
//if the value already is formatted correctly,
//write it to the new file