douyuanqia665858 2015-10-14 00:33
浏览 28
已采纳

格式化txt文件

I need to import csv file with php getcsv function but the file is not well formated and cannot import it. After uploading the file, I'd like to delete all " inside the file to have a proper file with ; for each field.

This is an example of my file:

"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email@gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email@gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email@gmail.com;070000000"

I think I would need to read each line of the file,and maybe use str_replace but I don't know how to write the new file...

  • 写回答

1条回答 默认 最新

  • doufanglian7585 2015-10-14 01:13
    关注

    Assuming you can get your code into a text string, you can just replace/remove the double-quotes. Then parse the text and get it into a format that will support fputcsv().

    When writing the folder, be sure to check that your user has permissions to write to this folder (for example if the parent folder has permissions drwxr-xr-x, you can fix it with chmod g+w folder_name).

    <?php
        // sample text to parse
        $some_text = '"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
        "M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email@gmail.com;010000000"
        "M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email@gmail.com;060000000"
        "M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email@gmail.com;070000000"';
    
        // remove quotes
        $final_text = str_replace('"', '', $some_text);
    
        // create array of rows by searching for new lines
        $data = str_getcsv($final_text, "
    ");
    
        // create an empty array to save our final csv data
        $final_csv = array();
    
        // loop thru the array and save to the final csv data
        foreach ($data as $value) {
                // before saving to final csv data, split row into individual column items 
                $value_array = explode(";", $value);
                $final_csv[] = $value_array;
        }
    
        // helper debugger to show data before writing it
        echo "<pre>";
        print_r($final_csv);
        echo "</pre>";
    
        // create a new file for writing or open and truncate to 0
        $fp = fopen('file.csv', 'w');
    
        // write to file from final csv data
        foreach ($final_csv as $fields) {
            fputcsv($fp, $fields);
        }
    
        // close file
        fclose($fp);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度