将CSV文件从服务器下载到本地目录

时间:2015-10-07 09:19:25

标签: php jquery csv

我编写了一个脚本,在其中创建CSV文件并将其保存在服务器的目录中。 CSV文件包含查询的属性。 使用Jquery和Ajax按钮单击执行整个过程。

我现在要做的是能够在本地保存生成的CSV。我发现了类似的问题,但我没有找到关于如何创建一个对话框的答案,该对话框将提示客户端指定保存文件的位置。

这是我的Jquery代码的一部分:

var nodeId = 'something';
var ajaxurl = 'requestsII/exportNodeData.php', // script to run
        data =  {nodeId:nodeId}; // data to pass
        $.post(ajaxurl, data, function (response) {     
                //alert(response);

        }); 

这是我的PHP脚本:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");  // EDITED

if ($db) {
    $stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId');
    $stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId));

    #$results=$stmt->fetchAll(PDO::FETCH_OBJ);
    #$json=json_encode($results);
    #echo($json);

    $filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv';

    $data = fopen($filename, 'w');

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
    }

    fclose($data);

}

echo($data); // EDITED

问题是如何在本地下载我在PHP脚本中创建的CSV文件?

2 个答案:

答案 0 :(得分:1)

试试此代码

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";

修改

尝试此代码

if ($db) 
{
    $stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS     "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type  IN (:typeI, :typeII) AND kodpop = :nodeId');
$stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId));

#$results=$stmt->fetchAll(PDO::FETCH_OBJ);
#$json=json_encode($results);
#echo($json);

$filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv';



header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$filename);  


while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    print_r($row);
}
}

答案 1 :(得分:1)

毕竟我没有使用上面的方法而且我做到了,这样做很好,而且更直接:

public static void subscribe()
{
    EventLogWatcher watcher = null;
    try
    {
        EventLogQuery subscriptionQuery = new EventLogQuery(
            "Security", PathType.LogName, "*[System/EventID=4624]");

        watcher = new EventLogWatcher(subscriptionQuery);

        // Make the watcher listen to the EventRecordWritten
        // events.  When this event happens, the callback method
        // (EventLogEventRead) is called.
        watcher.EventRecordWritten +=
            new EventHandler<EventRecordWrittenEventArgs>(
                EventLogEventRead);

        // Activate the subscription
        watcher.Enabled = true;

        for (int i = 0; i < 5; i++)
        {
            // Wait for events to occur. 
            System.Threading.Thread.Sleep(10000);
        }
    }
    catch (EventLogReadingException e)
    {
        Log("Error reading the log: {0}", e.Message);
    }
    finally
    {
        // Stop listening to events
        watcher.Enabled = false;

        if (watcher != null)
        {
            watcher.Dispose();
        }
    }
    Console.ReadKey();
}

// Callback method that gets executed when an event is
// reported to the subscription.
public static void EventLogEventRead(object obj,
    EventRecordWrittenEventArgs arg)
{
    // Make sure there was no error reading the event.
    if (arg.EventRecord != null)
    {
        //////
        // This section creates a list of XPath reference strings to select
        // the properties that we want to display
        // In this example, we will extract the User, TimeCreated, EventID and EventRecordID
        //////
        // Array of strings containing XPath references
        String[] xPathRefs = new String[9];
        xPathRefs[0] = "Event/System/TimeCreated/@SystemTime";
        xPathRefs[1] = "Event/System/Computer";
        xPathRefs[2] = "Event/EventData/Data[@Name=\"TargetUserName\"]";
        xPathRefs[3] = "Event/EventData/Data[@Name=\"TargetDomainName\"]";
        // Place those strings in an IEnumberable object
        IEnumerable<String> xPathEnum = xPathRefs;
        // Create the property selection context using the XPath reference
        EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

        IList<object> logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
        Log("Time: ", logEventProps[0]);
        Log("Computer: ", logEventProps[1]);
        Log("TargetUserName: ", logEventProps[2]);
        Log("TargetDomainName: ", logEventProps[3]);
        Log("---------------------------------------");

        Log("Description: ", arg.EventRecord.FormatDescription());
    }
    else
    {
        Log("The event instance was null.");
    }
}

这是ajax请求,我执行该请求是为了创建CSV文件(也是压缩的)。然后我使用这一行:

var ajaxurl = 'exportNodeData.php', // script to run
                data =  {nodeId:nodeId}; // data to pass
                $.post(ajaxurl, data, function (response) {     
                    document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';

                }); 

为了强制下载文件。