将数据发送到PHP页面以制作电子表格


Sending data to PHP page to make a spreadsheet out of it

由于某种原因,当我尝试将JSON数据发送到PHP页面(在那里它作为电子表格下载)时,它运行时没有错误,但不会显示下载电子表格的提示。JSON的生成没有问题(我已经让PHP页面在服务器上创建了文件,然后尝试在不创建文件的情况下下载它)。

以下是将JSON数据发送到服务器的JavaScript代码:

function writeToSpreadsheet()
{
    // get the json for #theTable
    var tableJSON = tableToJSON("tr:not(#titleRow)");
    //alert(tableJSON);
    alert("Sending table data to be written to the spreadsheet...");
    $.post('/ResearchProject/tableContent/exportTable.php', {'table': tableJSON}).done(
        function(response) { alert(((response == '') ? response : (tableJSON.title + ' written to file!')));})
        .fail(function (xhr, ajaxOptions, thrownError) { alert("ERROR:" + xhr.responseText+" - "+thrownError); });
}

这是exportTable.php

<?php
    function cleanData(&$str)
    {
        $str = preg_replace("/'t/", "''t", $str);   // escaping all of the tabs 
        $str = preg_replace("/'r?'n/", "''n", $str);    // escaping any and all cases of carriage return
        // if there is a single double-quote in the string, we wrap the string in quotes, replace every single double-quote with double double-quotes, and 
        //  end with a double-quote
        if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';  
    }
    // the data is coming from a JSON object that is being sent here
    if (isset($_POST['table']))
    {
        $tableJSON = $_POST['table'];   # somehow, this is already a PHP array (exactly the one we need)!!
        // get the name of the table from the $tableJSON
        $tableName = $tableJSON['title'];
        // get the title row from $tableJSON
        $titleRow = $tableJSON['titleRow'];
        // fix the titleRow
        foreach ($titleRow as $heading)
        {
            $heading = trim(preg_replace('/'s+/', ' ', $heading));
        }
        // get the rows from $tableJSON
        $rows = $tableJSON['rows'];
        // form the filename from the tableName
        $fileName = $tableName . '.xls';
        // here, we download the file without even creating it
        header("Content-Disposition: attachment; filename='"$fileName'"");
        header("Content-Type: application/vnd.ms-excel");
        // we echo the titleRow first
        array_walk($titleRow, 'cleanData');
        echo implode(chr(9), $titleRow) . "'r'n";
        ?>
<script>console.log('Title row written to file.');</script>
<?php           
        // now we echo the data
        foreach($rows as $row)
        {
            array_walk($row, 'cleanData');
            echo implode(chr(9), $row) . "'r'n";
?>
<script>console.log('Data row written to file.');</script>
<?php           
        }
    }
    else 
    {
        echo 'You sent me no data :('n';
    }
?>

好的,MikeWarren,我该如何测试

您可以通过从下拉菜单中选择一个表格并单击此处的"将表格导出到电子表格"按钮来测试它:http://dinotator.biokdd.org/ResearchProject/tableViewer.php

我正在尝试将HTML页面上的表转换为JSON对象,然后下载。因此,我需要将数据POST到PHP页面,对吧?(查询字符串不起作用。)

查询字符串不起作用,因为您使用的是jQuery的$.post调用,这意味着您的数据是在请求的正文中发送的,而不是GET使用的查询字符串。对于JSON,您确实希望使用POST。

至于哪里出了问题,您需要使用JSON_decode将JSON解码为PHP数组。不幸的是,它不能简单地处理JSON

所以最有可能你会想做:

// now a poorly named variable
$tableJSON = json_decode($_POST['table']);

另外,在Ajax中,$.post确实接受.fail()侦听器,但它不作为回调的一部分传递任何错误数据。因此,如果你想处理传入的响应错误,你需要使用$.ajax:

$.ajax({
    type: "POST",
    url: "/your/url.php",
    dataType: "json",
    error: errorCallback
});

最后,看看代码的结构,如果您真的试图保存到文件中,您将需要更多的逻辑。现在,您只需渲染该表,然后将其作为响应返回,该响应将显示在done函数中。您将添加更多的逻辑,以便使其真正下载。这个问题引出了你的确切问题。

祝你好运!

我在互联网上发现了很多关于如何解决这个问题的糟糕建议。这里的一个答案也不起作用(

我决定从我的一个朋友那里得到建议,我和他决定采用这种方法:

  • 让我的exportData.php简单地将数据写入$_SESSION,回显JSON编码的"成功",然后退出
  • 在退出时,在客户端,如果收到"成功",让JavaScript打开一个新的选项卡,指向我创建的名为downloadFile.php的文件,该文件实际上负责下载

为什么在文件之间发送数据不起作用

下载数据需要设置正确的标题并打印数据。当您将数据发送到文件以执行此操作时(通过AJAX),数据打印到的缓冲区是用于响应的缓冲区。你可以通过说这样的话来看到这一点success: function(response) { alert(response); },并看到您"下载"的数据不会被下载,而是在屏幕上打印出来。

但是,如果您转到该文件,而不是简单地将数据传递给它,那么只要它可以访问您试图下载的数据,您的数据就会下载。你可以在这里看到这样的例子:www.the-art-of-web.com/php/dataexport/。在这些例子中,数据是"静态的"(也就是说,在下载之前,只存在于该php文件的范围内)。

然后我们看到我们应该让另一个文件来处理下载。以下是它的内容应该是什么样子:

<?php
    if (!isset($_SESSION))
        session_start();
    function cleanData(&$str)
    {
        $str = preg_replace("/'t/", "''t", $str);   // escaping all of the tabs 
        $str = preg_replace("/'r?'n/", "''n", $str);    // escaping any and all cases of carriage return
        // if there is a single double-quote in the string, we wrap the string in quotes, replace every single double-quote with double double-quotes, and 
        //  end with a double-quote
        if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';  
    }
    // get the data from $_SESSION
    if (isset($_SESSION))
    {
        $fileName = $_SESSION['fileName'];
        $titleRow = $_SESSION['titleRow'];
        $rows = $_SESSION['rows'];
        // set the excel headers 
        header("Content-Type: application/vnd.ms-excel");
        //header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename='"$fileName'"");
        header("Pragma: no-cache");
        header("Expires: 0");
        // attempt download
        array_walk($titleRow, 'cleanData');
        echo implode(chr(9), $titleRow) . "'r'n";
        // now we echo the data
        foreach($rows as $row)
        {
            array_walk($row, 'cleanData');
            echo implode(chr(9), $row) . "'r'n";
        }
    }
    else
    {
        die('Problem with session variable. Data could not be sent for download.');
    }
    exit;
?>

当然,在执行此操作之前,请确保已将'fileName''titleRow''rows'写入$_SESSION

这应该可以帮助任何有问题的人通过PHP将HTML表下载到Excel电子表格,,最棒的是,你不必通过下载整个库来膨胀你的服务器,因为这可能是一个按钮的功能