Trinity76
Trinity76

Reputation: 665

php how to convert data from csv file?

I have a csv file that has data like

shelfmark, centuries
foo-0001, 2000s;
bar-1234, 1200s, 1300s;
baz-IK-1234, 0100s, 0200s, 0300s;
and so on...

I want to import the data and convert it to a format that has only two columns:

shelfmark, century
foo-0001, 2000s;
bar-1234, 1200s;
bar-1234, 1300s;
baz-IK-1234, 0100s;
baz-IK-1234, 0200s;
baz-IK-1234, 0300s;
and so on...

And write it in a new csv-file.

I need help with the code of creating new rows if a row contains more than one century value.

My attempt:

<?php
    $csv = array_map('str_getcsv', file($file));
    array_walk($csv, function(&$a) use ($csv) {
      // check if row has more than two column entries
      if
      // if so then split the first century value into a new row 
      // do so until no more century value is in the row left and continue with next row
      $data = array_combine($csv[0], $a);
    });
    // write into new csv file
    $fp = fopen('php://output', 'w');
    foreach ( $data as $line ) {
        $val = explode(",", $line);
        fputcsv($fp, $val);
    }
    fclose($fp);

?> 

Upvotes: 0

Views: 45

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

You can simplify the process by looping over the final content and just taking off the line header ( 'foo-0001' ) using array_shift() and then adding this to each of the remaining elements in the array.

This uses fwrite() to maintain the content format.

$csv = array_map('str_getcsv', file($file));
// Take the titles out of the main list of lines
$titles = array_shift($csv);
$fp = fopen('php://output', 'w');
// Add the header row
fwrite($fp, implode(",", $titles).PHP_EOL);
foreach ( $csv as $line ) {
    $header = array_shift($line);   // Remove the first part from the array
    foreach ( $line as $entry )  {
        fwrite($fp, $header.",". trim($entry,";").";".PHP_EOL);
    }
}
fclose($fp);

Upvotes: 1

Related Questions