简体   繁体   English

如何使用PHP将其写入文件?

[英]How Can I Write this to File Using PHP?

I have been working with a script to change my CSV file to Tab Delimited. 我一直在使用脚本将我的CSV文件更改为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: 这是脚本:

<?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. 这是您可以将逗号分隔的CSV更改为以制表符分隔的方式。 However, I don't see the benefits of doing this. 但是,我没有看到这样做的好处。 I think comma delimited CSVs are much less prone to errors. 我认为以逗号分隔的CSV不太容易出错。

<?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. 您需要将调用fmpn中的模式从r更改为以写入模式打开文件的模式。 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+ . 我猜你要覆盖,在这种情况下你可以选择ww+

Check out the manual for fopen and fwrite . 查看fopenfwrite的手册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM