调整CSV文件中的标题

时间:2015-04-10 19:05:12

标签: php csv logging header

我的PHP网站上有一个日志例程,它将数据放在每日CSV文件中。这是代码:

public function generateLogPMWeb($action){
    session_start('usuario');

    $head_data = "HOSPEDE_CODIGO" . ";" . "RESERVA_CODIGO" . ";" . "HOSPEDE_NOME" . ";" . "HOSPEDE_SOBRENOME" . ";" . "HOSPEDE_EMAIL" . ";" . "RESERVA_DESCRICAOSISTEMA" . ";" . "RESERVA_CODIGOLOCALIZADOR" . ";" . "RESERVA_CODIGOHOTEL" . ";" . "RESERVA_DATARESERVA" . ";" . "RESERVA_DATACHECKIN" . ";" . "RESERVA_DATACHECKOUT" . ";" . "ACAO" . ";\n";
    file_put_contents(Config::retorna("document_root", "root").'/logPMWeb/logPMWeb_'.date("Ymd").'.csv', $head_data, FILE_APPEND); // MUDAR AQUI

    $logPMWeb  = $_SESSION['usuario']['id'] . ";" . date('YmdHis') . "_" . $_POST['idHotel'] . "_" . $_SESSION['usuario']['id'] . ";" . $_SESSION['usuario']['nome'] . ";" . $_SESSION['usuario']['sobrenome'] . ";" . $_SESSION['usuario']['email'] . ";" . "IC"
            . ";" . date('YmdHis') . "_" . $_POST['idHotel'] . "_" . $_SESSION['usuario']['id'] . ";" . $_POST['idHotel'] . ";" . date('Y-m-d H:i:s') . ";" . $_SESSION['buscaReserva']['dataInicio'] . ";" . $_SESSION['buscaReserva']['dataFim']
            . ";" . preg_replace('/^\s+|\n|\r|\s+$/m', '', $action) . ";\n";
    //Save string to log, use FILE_APPEND to append.
    file_put_contents(Config::retorna("document_root", "root").'/logPMWeb/logPMWeb_'.date("Ymd").'.csv', $logPMWeb, FILE_APPEND);
}

但是我的CSV文件上有重复的标题行。我只需要在文件的第一行显示标题。

最好的办法是什么?

1 个答案:

答案 0 :(得分:0)

使用如下所示的file_exists ... http://php.net/manual/en/function.file-exists.php

public function generateLogPMWeb($action){
    session_start('usuario');

    $logfile = Config::retorna("document_root", "root").'/logPMWeb/logPMWeb_'.date("Ymd").'.csv'

    $head_data = "HOSPEDE_CODIGO" . ";" . "RESERVA_CODIGO" . ";" . "HOSPEDE_NOME" . ";" . "HOSPEDE_SOBRENOME" . ";" . "HOSPEDE_EMAIL" . ";" . "RESERVA_DESCRICAOSISTEMA" . ";" . "RESERVA_CODIGOLOCALIZADOR" . ";" . "RESERVA_CODIGOHOTEL" . ";" . "RESERVA_DATARESERVA" . ";" . "RESERVA_DATACHECKIN" . ";" . "RESERVA_DATACHECKOUT" . ";" . "ACAO" . ";\n";
    if (!file_exists($logfile)) {
       file_put_contents($logfile, $head_data, FILE_APPEND); // MUDAR AQUI
    }

    $logPMWeb  = $_SESSION['usuario']['id'] . ";" . date('YmdHis') . "_" . $_POST['idHotel'] . "_" . $_SESSION['usuario']['id'] . ";" . $_SESSION['usuario']['nome'] . ";" . $_SESSION['usuario']['sobrenome'] . ";" . $_SESSION['usuario']['email'] . ";" . "IC"
            . ";" . date('YmdHis') . "_" . $_POST['idHotel'] . "_" . $_SESSION['usuario']['id'] . ";" . $_POST['idHotel'] . ";" . date('Y-m-d H:i:s') . ";" . $_SESSION['buscaReserva']['dataInicio'] . ";" . $_SESSION['buscaReserva']['dataFim']
            . ";" . preg_replace('/^\s+|\n|\r|\s+$/m', '', $action) . ";\n";
    //Save string to log, use FILE_APPEND to append.
    file_put_contents($logfile, $logPMWeb, FILE_APPEND);
}