开发者

overwriting column with fputcsv

开发者 https://www.devze.com 2022-12-21 17:29 出处:网络
I wan开发者_JAVA百科t to parse, process and then overwrite only 1 specific column in a csv file, I\'m fine with the first two steps but am having issues with the third. Here\'s what I have so far:

I wan开发者_JAVA百科t to parse, process and then overwrite only 1 specific column in a csv file, I'm fine with the first two steps but am having issues with the third. Here's what I have so far:

<?php
$fh = fopen("data.csv", "r");
$row = 1;
while (($data = fgetcsv($fh, 1024, ",")) !== FALSE) {
$get = $data[2];
$uc = ucwords(strtoupper($get));
echo $uc;
}
?>

That displays fine, I just need the processed content to be written back into it's original column. I know this is done with fputcsv, but I can't seem to get it to work:

$fp = fopen('data.csv', 'w');
fputcsv($fp, $uc, ",");
fclose($fp); 

That just wipes the entire file. Same thing when using fwrite. Any ideas?

Thanks.


Please note that both functions work for lines, not for the whole file.

So you will have to rebuild it when you write out, something like:

<?php
$list = array (
   'aaa,bbb,ccc,dddd',
   '123,456,789',
   '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
   fputcsv($fp, split(',', $line));
}

fclose($fp);
?>

Untested

<?php
$fh = fopen("data.csv", "r");
$row = 1;
$list=array();
while (($data = fgetcsv($fh, 1024, ",")) !== FALSE) {
    $data[2] = ucwords(strtoupper($data[2]));
    $list[]=$data; // collect lines
}
fclose($fh);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
   fputcsv($fp, $line);
}

fclose($fp);
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消