I need PHP help opening a CSV file into an array, altering the data, and then overwriting the original CSV file with the altered data

StackOverflow https://stackoverflow.com/questions/6372163

  •  28-10-2019
  •  | 
  •  

Question

I need to pull data from a CSV file to use in reporting. However, the exporting software does not have the capability to export it in a useful format. Using PHP I would like to take a CSV file with data like:

'Time','Month And Year','Count'
'8 Hours','Apr 2011','127'
'6 Hours','Apr 2011','45'
'4 Hours','Apr 2011','23'
'2 Hours','Apr 2011','122'
'8 Hours','Dec 2010','29'
'6 Hours','Dec 2010','8'
'4 Hours','Dec 2010','1'
'2 Hours','Dec 2010','64'
etc...

And turn it into this:

Time,Dec 2010,Jan 2011,Feb 2011,Mar 2011,Apr 2011,May 2011
8 Hours,126,47,115,77,127,110
6 Hours,45,18,62,38,42,31
4 Hours,23,3,11,8,15,18
2 Hours,122,93,185,144,128,70

At the moment, I have the code to open the CSV file using fgetcsv() and remove unwanted characters:

$lines = array();
$tempName = array();
$tempCount = array();
$tempTitle = array();
$items = array();

$fp = fopen('../data/data2.csv','r') or die("can't open data2.csv");

while($lines = fgetcsv($fp,4096,"\\n")) {

  for ($i = 0, $j = count($lines); $i < $j; $i++) {

    $lines[$i] = str_replace('\'', '', $lines[$i]);
    $lines[$i] = str_replace('A: ', '', $lines[$i]);
    $lines[$i] = str_replace('B: ', '', $lines[$i]);
    $lines[$i] = str_replace('C: ', '', $lines[$i]);
    $lines[$i] = str_replace('D: ', '', $lines[$i]);

  }
}

fclose($fp) or die("can't close volume2.csv");

This stores the lines of the CSV file into comma delimited rows, which makes the $lines array look like:

Time,Month And Year,Count
8 Hours,Apr 2011,127
6 Hours,Apr 2011,45
4 Hours,Apr 2011,23
2 Hours,Apr 2011,122
8 Hours,Dec 2010,29
6 Hours,Dec 2010,8
4 Hours,Dec 2010,1
2 Hours,Dec 2010,64
etc...

Now what I need to do is store the data in the correct order inside of one or more arrays in order to be able to export it back into the CSV file.

I tried using:

for ($h = 0, $k = count($lines); $h < $k; $h++) {
  $items = preg_split("/[,]+/",$lines[$h]);
}

and then placing the correct data into arrays using a case statement, but it hangs up, so I must be doing something wrong. (Not to mention this code is not optimized.)

Any ideas on where I can go from here? Thanks!

Was it helpful?

Solution

You're using fgetcsv() in the wrong way and having it read in multiple lines at once.

Modify your code to use:

while($line = fgetcsv($fp)) {

}

and in each iteration parse a row at a time.

if you want to write this back to a CSV file you shoudl be able to do something like:

$out = array();
while($line = fgetcsv($fp)) {
    // modify fields as you need to
    $out[] = implode(",", $line);
}

// now you can write implode("\n", $out) out as the modified data
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top