Change csv to text fromat and change the formatting

Hi Guys,

I have a csv file that looks like below :

IMSI ICCID MSISDN FAX ISDN56 ISDN64 APN
901112112542731 898709912412543000 870772332028 870782546182 870782548300 870782551182 c2c.bgan.inmarsat.com
901112112542731 898709912412543000 870772332028 870782546182 870782548300 870782551182 c2c.bgan.inmarsat.com

Basically I want it to look as follow : It must be saved then as a normal text

======= Package 1 ==========

IMSI 901112112542731
ICCID 898709912412542731
MSISDN 870772332028
FAX 870782546182
ISDN56 870782548300
ISDN64 870782551182
APN c2c.bgan.inmarsat.com

======= Package 2 ==========

IMSI 901112112542731
ICCID 898709912412542731
MSISDN 870772332028
FAX 870782546182
ISDN56 870782548300
ISDN64 870782551182
APN c2c.bgan.inmarsat.com

========= END OF PACKAGES ==========
= Total Processed: 2
= Date Processed: 2012-10-29

Have you attempted anything? This should be pretty easy. Maybe str_getcsv() will help get you started.

This is what I have so far, it will only display the array for me, now I need to write that array to a file.

[php]
<?php

print_r(buildStock(‘example.csv’));

function buildStock($File) {
$handle = fopen($File, “r”);
$fields = fgetcsv($handle, 1000, “,”);

    while($data = fgetcsv($handle, 1000, ",")) {
        $detail[] = $data;
    }
    
    $x = 0;
    $y = 0;
        
    foreach($detail as $i) {
        foreach($fields as $z) {
            $stock[$x][$z] = $i[$y];
            $y++;
        }
        $y = 0;
        $x++;
    }
    return $stock;
}


    ?>[/php]

You are calling fgetcsv twice which is unnecessary since the first line is always going to be your fields. Also, your use of fgetcsv doesn’t match the csv format you posted. Is your delimiter a tab or a comma?

It would be a comma

OK, your function works as it should but I will show you how you can get $fields without the second call, as well as sort the array easier.

[php]
function buildStock($File) {
$handle = fopen($File, “r”);
$detail = array();
while($data = fgetcsv($handle, 1000, “,”)) {
$detail[] = $data;
}
$fields = array_shift($detail); // shift fields off the beginning of $detail array

// sort data
$i = 1;
$stock = array();
foreach($detail as $data) {
	foreach($data as $key => $value) {
		$stock[$i][$fields[$key]] = $value;
	}
	$i++;
}
return $stock;

}
[/php]

From here, all you have to do is build your new output, for example:

[php]
$myArray = buildStock(‘example.csv’);
foreach($myArray as $num => $data) {
echo "Package " . $num . “\n\n”;
foreach($data as $key => $value) {
echo $key . “\t” . $value . “\n”;
}
echo “\n”;
}
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service