使用JavaScript和PHP生成文件

时间:2015-01-25 02:16:33

标签: javascript php jquery

我正在尝试生成要下载的文件。使用JavaScript,我调用一个PHP文件来处理我的请求,并以一种可以下载它的方式发回结果。但它不是让它可供下载,而只是显示代码。

PHP

function export()
{
    // Get a database object.   
    $db = JFactory::getDbo();

    // Create a new query object.
    $query = $db->getQuery(true);

    // Select fields to get.
    $fields = array(
        $db->quoteName('params')
    );

    // Conditions for which records should be get.
    $conditions = array(
        $db->quoteName('element') . ' = ' . $db->quote('plugin_name'), 
        $db->quoteName('folder') . ' = ' . $db->quote('system')
    );

    // Set the query and load the result.
    $query->select($fields)->from($db->quoteName('#__extensions'))->where($conditions);
    $db->setQuery($query);   
    $results = $db->loadResult(); 

    // Namming the filename that will be generated.
    $name      = 'file_name';
    $date      = date("Ymd");
    $json_name = $name."-".$date;

    // Clean the output buffer.
    ob_clean();

    echo $results;
    header('Content-disposition: attachment; filename='.$json_name.'.json');
    header('Content-type: application/json');
}

的JavaScript

function downloadFile() {
    var fd = new FormData();
    fd.append('task', 'export');
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", uploadComplete, false);
    xhr.open("POST", "my_php_file");
    xhr.send(fd);
}

HTML文件

<button class="btn btn-primary btn-success" type="button" onclick="downloadFile()"></button>

更新我的代码

2 个答案:

答案 0 :(得分:0)

在输出数据之前,您需要调用任何header函数调用。否则,您将收到标题“已发送标题”警告,并且不会设置标题。

示例:

...
// Namming the filename that will be generated.
$name      = 'file_name';
$date      = date("Ymd");
$json_name = $name."-".$date;

header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');

// Clean the output buffer.
ob_clean();

echo $results;

答案 1 :(得分:0)

一个例子

<?php
ob_start();

echo "some content to go in a file";

$contentToGoInFile = ob_get_contents(); //this gets the outputted content above and puts it into a varible/buffer
ob_end_clean();
header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');
echo $contentToGoInFile;
exit; //stops execution of code below

代码示例

$results = $db->loadResult(); 

// Namming the filename that will be generated.
$name      = 'file_name';
$date      = date("Ymd");
$json_name = $name."-".$date;

ob_start();
echo $results;
$contentToGoInFile = ob_get_contents(); //this gets the outputted content above and puts it into a varible/buffer
ob_end_clean();
header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');
echo $contentToGoInFile;
exit