duanjian7617 2012-08-30 22:52
浏览 17
已采纳

如何使这个PHP代码更高效? (在CSV文件中编辑一行)

This code works, but I just hacked it together with my limited knowledge of PHP and I'm sure there's a more elegant and efficient way to go about it. If you'd be so kind as to point out how I can improve, that would be great!

So I have a CSV file, structured like so:

Code        Class     Value    Status      Date Created    Date Redeemed
========================================================================
a51f3g45    gold      50       valid       2012-08-20      
4f6a2984    silver    200      redeemed    2012-08-23      2012-08-27      
gf3eb54b    gold      150      valid       2012-08-30      

etc...

The user fills out a form to change the Class, Value, and Status fields of a given line. I cobbled together the following code to replace the old values with the new ones:

$file = 'codes.csv';
$old_csv_string = file_get_contents($file);

preg_match('/('.$_POST['code'].',.*,.*,.*,.*,.*)
/',$old_csv_string,$matches);
$old_row = $matches[1];

preg_match('/'.$_POST['code'].',(.*,.*,.*),.*,.*
/',$old_csv_string,$matches_part);
$old_row_part = $matches_part[1];

$new_row_part = $_POST['class'].",".$_POST['value'].",".$_POST['status'];
$new_row = str_replace($old_row_part,$new_row_part,$old_row);
$new_csv_string = str_replace($old_row,$new_row,$old_csv_string);
file_put_contents($file,$new_csv_string);

So can I do better than 10 lines of code? Any advice would be greatly appreciated :)

Note: I tried using fgetcsv, but I couldn't figure out how to find the unique code within a 2D array, then replace its siblings.

  • 写回答

2条回答 默认 最新

  • du5407 2012-08-30 23:58
    关注

    Why are you doing this ? I think you should store the data in a SQL table.
    Each time user update data, do it in the table.
    If you want the CSV to be downloadable at any moment. Use a .htaccess to redirect your.csv to csv_generator.php only if your.csv does not exist.
    csv_generator.php will regenerate the whole csv if it does not exist, save it on hard drive for later use, and send it with correct mime/type in header (so it's transparent for user). User don't see he is requesting a php page.
    Then you need to delete the csv on hard drive each time someone update the data (so it will be regenerated on next request)

    I think this is the way to have an always ready to download csv online.

    Do you know google doc does this ? Users can change data in a spreadsheet wich is available to download as a csv from a url (you need to publish this spreadsheet as a csv file).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?