Use fputcsv() to insert a row at the top of a csv file?

99封情书 提交于 2021-02-16 17:05:39

问题


Pretty simple question. I know how to use fputcsv() to insert a row into a csv but it inserts it at the bottom. Is there a way to use it to insert something at the top of the csv?

I need to add a header to an existing csv file.

Any help on this would be great.

Thanks!


回答1:


fputcsv() inserts data at the file pointer, so you can rewind() the pointer to the beginning of the file.

rewind($handle);
fputcsv($handle, $fields);

Alternately, you can simply open the file with the pointer at the beginning:

$handle = fopen('yourfile.csv', 'r+');
fputcsv($handle, $fields);



回答2:


Basically with:

fseek($file, 0);
fputcsv($file, $titles, ',');

I think this is duplicate for PHP: How can I add newly one row at the top of the csv file using fputcsv?



来源:https://stackoverflow.com/questions/16219049/use-fputcsv-to-insert-a-row-at-the-top-of-a-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!