导出为CSV会将数据放在一行而不是新行上

时间:2013-03-01 00:21:37

标签: php javascript export-to-csv

我将数据导出为CSV,而当我使用"\r\n"时,它只是在一行上输出数据而不是在标题行下面的新行上输出每组数据,即:

name | address | phone | email | greg | 2 old street | 09236462942 | greg343@gmail.com | michael | 2 new street | 0927464623 | michael343@gmail.com | ...

代码如下:

JS

var file = "Database.csv";

allData=name+","+address+","+phone+","+email;
        allData=allData.replace(/[\\]/g,'');
        saving();

function saving(){
    $.ajax({
        type: 'POST',
        url: 'save.php',
        timeout: 5000,
        data: { data: allData, filename: file },
        error: function() {localStorage["allData"]=allData; wiadomosc("Internet conection error. But don't worry, your data will be stored when conection will be stable.");},
        success: function() {localStorage["allData"]="";}
    });
}

PHP

<?php
if(isset($_POST["filename"]) == true && isset($_POST["data"]) == true){
    $fp = fopen($_POST["filename"], "a+");

    if($fp !== null){
        fputs($fp, $_POST["data"] . "\r\n");
        fclose($fp);
    }
}
?>

1 个答案:

答案 0 :(得分:1)

allData似乎是一个全局变量。根据你们其余的代码,几乎任何事情都可能发生。您应该明确地将allData传递给saving。并在浏览器端(例如使用Firebug)和服务器端(例如使用Netbeans)进行调试。

此行也是纯邪恶

$fp = fopen($_POST["filename"], "a+");

这样你几乎可以覆盖系统(服务器)上的任何东西!

不要检查isset($_POST["filename"]) == true。要么isset($_POST["filename"]) === true(在这种情况下不需要),要么只做isset($_POST["filename"])

编辑:

这应该可以避免JS中的一些问题:

var allData=name+","+address+","+phone+","+email;
        allData=allData.replace(/[\\]/g,'');
        saving(allData);

function saving(allData){
    $.ajax({...

这在PHP中:

function mk_safe_filename($name, $allow_subfolders=false)
{
    $f = trim($nazwa, './\\');
    if (!$allow_subfolders)
    {
        $f = strtr($f, array('\\'=>'__', '/'=>'__', '..'=>'_', ':'=>'_'));
    }
    else
    {
        $f = strtr($f, array('\\'=>'/', '..'=>'_', ':'=>'_'));
        $f = trim($f,'/');
    }
    return $f;
}
$file_name = mk_safe_filename($_POST["filename"]);

$fp = fopen($file_name, "a+");