Созданные файлы CSV загружаются пустыми, но имеют контент

Я написал следующий скрипт для создания файла CSV на основе содержимого из базы данных. Сам скрипт отлично работает, создает файл CSV и заполняет его, как и ожидалось. Проблема заключается в том, что когда файл загружается автоматически, он пуст, но при загрузке его с хост-сервера через FTP он заполняется информацией.

Файл загружается слишком рано, прежде чем файл будет успешно записан? Что-нибудь можно сделать, чтобы решить эту проблему?

<?php

// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");

$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');

$handle = fopen($filename, 'w');
fputcsv($handle, $headers, ',', '"');

$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);

while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);

$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);

fputcsv($handle, $row, ',', '"');
}

// rewind the "file" with the csv lines
fseek($handle, 0);

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');

// make php send the generated csv lines to the browser
fpassthru($handle);

fclose($handle);

?>

0

Решение

После дальнейшего тестирования и нахождения аналогичного поста по теме я нашел исправление. Вместо того, чтобы использовать fopen () для файла, я записал данные в память, и теперь она работает правильно.

<?php

// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");

$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');

//$handle = fopen($filename, 'w');
$handle = fopen('php://memory', 'w');
fputcsv($handle, $headers, ',', '"');

$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);

while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);

$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);

fputcsv($handle, $row, ',', '"');
}

// rewind the "file" with the csv lines
fseek($handle, 0);

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');

// make php send the generated csv lines to the browser
fpassthru($handle);

fclose($handle);

?>
2

Другие решения

попробуйте поставить это

// Establish the MySQL Database Connection
include_once("./include/database.php");
include("functions.php");

ob_start(); //start output buffering

$filename = 'devices.csv';
$headers = array('ID', 'Device', 'Name', 'Type', 'Scope', 'OS', 'Datacenter');

$handle = fopen($filename, 'w');
fputcsv($handle, $headers, ',', '"');

$sql = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);

while($results = mysql_fetch_object($sql))
{
$type = getDeviceType($results->type, $dp_conn);
$scope = getDeviceScope($results->scope, $dp_conn);
$os = getOS($results->os, $dp_conn);
$datacenter = getDatacenter($results->datacenter, $dp_conn);

$row = array(
$results->id,
$results->device_id,
$results->name,
$type,
$scope['name'],
$os,
$datacenter
);

fputcsv($handle, $row, ',', '"');
}

ob_end_clean(); //ending output buffering.

// rewind the "file" with the csv lines
fseek($handle, 0);

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');

// make php send the generated csv lines to the browser
fpassthru($handle);

fclose($handle);
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector