开发者

How Can I Write this to File Using PHP?

I have been working with a script to change my CSV file to Tab Delimited. It seems to work great, but it is read-only. How do I go about actually writing the changes to the file? Here is the script:开发者_JS百科

<?php
$myfile = "/path/to/my.csv";
$csv_fp = fopen ($myfile, "r");
$rows = 0;
      while ($data = fGetCsv ($csv_fp, 10000, ",")) 
{
$num = count($data);
for ($c=0; $c < $num; $c++) {
   echo $data[$c] . "<br />\n";
      }

$rows++;
}fclose ($csv_fp);  
?>


This is how you can change a comma delimited CSV to a tab delimited. However, I don't see the benefits of doing this. I think comma delimited CSVs are much less prone to errors.

<?php
$myfile = "/path/to/my.csv";
$csv_fread = fopen($myfile, 'r');

$rows = array();
while ($columns = fgetcsv($csv_fread, 10000, ",")) {
    $rows[] = $columns;
}
fclose($csv_fread);


$csv_fwrite = fopen($myfile, 'w');
foreach($rows as $row){
    fputcsv($csv_fwrite, $row, "\t");
}
fclose($csv_fwrite);
?>


You will need to change the mode in your call to fopen from r to one that opens the file in write mode. Which one you choose depends on what you want to do (append, overwrite). I am guessing that you want to overwrite, in which case you can choose w or w+.

Check out the manual for fopen and fwrite.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜