doudou201701 2014-12-14 11:56
浏览 150

使用fwrite的不需要的空格和错误的编码

I'm doing a simple **fwrite** in a csv file writing one line afte the other:

//Clean maybe empty entries of last winners
    $cleaned = array();
    $tick = 0;
    $debug = "";
    if (($fh = fopen(LAST_WINNERS_PATH, 'r+b')) !== FALSE) {
        if (flock($fh, LOCK_EX)) {
            while (($row = fgetcsv($fh, 300, ';')) !== FALSE) {
                $tick++;
                foreach ($row as $key => $value) {
                    $row[$key] = stripslashes($value);
                }
                if ($row[0] != '') {
                    array_push($cleaned, $row);
                }
            }
            array_reverse($cleaned);
            ftruncate($fh, 0);
            $count = count($cleaned);
            foreach ($cleaned as $key => $row) {
                $string = implode(";", $row);
                if ($key < $count -1) {
                    $string .= PHP_EOL;
                }
                fwrite($fh, $string);
            }
            flock($fh, LOCK_UN);
        } else {
        }
        fclose($fh);
    } else {
    }

Now I have two questions:

  1. Everything is in utf-8, but the csv file converts every time back to ANSI, when writing to it. Why and what can be don to prevent this?

  2. In front of the first line every time several whitespaces are added. How to avoid that?

  • 写回答

1条回答 默认 最新

  • douxing9641 2014-12-14 12:00
    关注

    For that problem its easier to use fputcsv

    http://php.net/manual/de/function.fputcsv.php

    Its made for such things.

    <?php
    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );
    
    $fp = fopen('file.csv', 'w');
    
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
    
    fclose($fp);
    ?>
    

    example from php.net.

    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测