Page is a not externally linkable
- Code, Content, and Presentation
-- PHP Server Side Scripting
---- Basics of extracting data from CSV files


jatar_k - 8:04 pm on Dec 18, 2003 (gmt 0)


Welcome to WebmasterWorld beatsie,

Anyone have any ideas or suggestions for an approach to this problem?

I am sure we can think of something ;)

your order of events seems fairly straight forward

1. open the source file for read
2. open destination file for write
3. get row from source
4. reformat
5. write to destination
6. repeat
7. close files

seems simple enough

1. open the source file for read
$sfp = fopen [ca.php.net]('/path/to/source.csv','r');

2. open destination file for write
$dfp = fopen('/path/to/destination.csv','w');

3. get row from source - we'll put this into a while loop to continuously get rows until we have none left
while ($row = fgetcsv [ca.php.net]($sfp,10000,",","")) {
}

4. reformat - since fgetcsv splits it up for us we are looking for the third element of the $row array

$goodstuff = str_replace [ca.php.net]("¦",",",$row[2]);
$goodstuff .= "\n";

we may need to intialize $goodstuff inside the loop to be safe

Note:Step 4 can be any type of reformatting that needs to be performed on the file contents. In this particular case we are removing fields but this would be the step where any reconstruction can be made.

5. write to destination
fwrite [ca.php.net]($dfp,$goodstuff);

6. repeat- the while loop takes care of this step as well

7. close files
fclose [ca.php.net]($sfp);
fclose($dfp);

so what does that leave us with?

<? 
$sfp = fopen('/path/to/source.csv','r');
$dfp = fopen('/path/to/destination.csv','w');
while ($row = fgetcsv($sfp,10000,",","")) {
$goodstuff = "";
$goodstuff = str_replace("¦",",",$row[2]);
$goodstuff .= "\n";
fwrite($dfp,$goodstuff);
}
fclose($sfp);
fclose($dfp);
?>

seems pretty straight forward, didn't test it obviously ;)

WebmasterWorld breaks pipes so ¦ must be replaced with an unbroken pipe

[edited by: jatar_k at 7:57 pm (utc) on Feb. 6, 2005]


Thread source:: http://www.webmasterworld.com/php/2349.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com