doujingxi3356 2016-04-11 16:04
浏览 77
已采纳

将多维Javascript数组保存到服务器端CSV

I'm trying to save a multidimensional Javascript array as a CSV file on the server. So far, my code creates the CSV file, but the file doesn't contain my array, and I'm not sure why.

(where outputData is established)

function dataSave(){
outputStr = JSON.stringify(outputData);
$.ajax({
    type: "POST",
    url: "csvout.php",
    data: outputStr,
    dataType: 'html',
});}

csvout.php:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<?php    
$array = json_decode($_POST['outputStr']);
$file = fopen("out/data.csv","w");
foreach ($array as $line){
    foreach ($line as $item){
        fputcsv($file,explode(',',$item));
        }
    }

fclose($file); 
?>

</head>
<body>
</body>
</html>

The data is an array of arrays like this one-- it's data obtained from the client, who is participating in a scientific experiment. Everything is a string.

0: "tuba.mp3"
1: "prac"
2: "1"
3: "0"
4: "type1"
5. "500"

0: "clap.mp3"
1: "main"
2: "0"
3: "0"
4: "type1"
5. "300"

[...]
  • 写回答

1条回答 默认 最新

  • doubu1853 2016-04-11 16:28
    关注

    You are passing a raw JSON string as your query parameter but are attempting to access it as a named parameter. Updated code:

    function dataSave(){
    outputStr = JSON.stringify(outputData);
    $.ajax({
        type: "POST",
        url: "csvout.php",
        data: { outputStr: outputStr },
        dataType: 'html',
    });}
    
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    
    <?php    
    $array = json_decode($_POST['outputStr']);
    adding var_dump($array); here produces NULL
    
    $file = fopen("out/data.csv","w");
    foreach ($array as $line){
        fputcsv($file,$item);
    }
    
    fclose($file); 
    ?>
    
    </head>
    <body>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同