保存Excel导出到文件位置PHP

时间:2016-06-16 19:29:08

标签: php mysql excel

我正在尝试将以下代码保存到服务器上的文件位置,任何人都可以提供帮助。目前它只是通过浏览器下载,但我想运行一个cron并保存在文件位置。

<?php
// Connection 

$conn=mysql_connect('**','**','**');
$db=mysql_select_db('SHP',$conn);

$filename = "stockbook.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
file_put_contents("http://kempfenterprises.com/dash/reports/stockbook.xls");
$user_query = mysql_query("select * from troy.stockbook ");
// Write data to file
$flag = false;
while ($row = mysql_fetch_assoc($user_query)) {
if (!$flag) {
    // display field/column names as first row
     echo implode("\t", array_keys($row)) . "\r\n";
        $flag = true;
     }
    echo implode("\t", array_values($row)) . "\r\n";
  }
?>

提前致谢

3 个答案:

答案 0 :(得分:0)

您可以使用file_put_contents在服务器中写入文件。

http://php.net/manual/en/function.file-put-contents.php

答案 1 :(得分:0)

<?php
$conn=mysql_connect('**','**','**');
$db=mysql_select_db('SHP',$conn);

$sql = "select * from troy.stockbook";
$qur = mysql_query($sql);

// Enable to download this file
$filename = "stockbook.csv";

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

$display = fopen("php://output", 'w');

$flag = false;
while($row = mysql_fetch_assoc($qur)) {
if(!$flag) {
  // display field/column names as first row
  fputcsv($display, array_keys($row), ",", '"');
  $flag = true;
}
fputcsv($display, array_values($row), ",", '"');
  }

fclose($display);
?>

这是使用fopen我现在如何添加我想要保存的位置

答案 2 :(得分:0)

<?php
$conn = mysql_connect('**', '**', '**');
$db = mysql_select_db('SHP', $conn);
$sql = "select * from troy.stockbook";
$qur = mysql_query($sql);
// Enable to download this file
$filename = "stockbook.csv";
$display = fopen("php://output", 'w');
$data = "";
$flag = false;
while ($row = mysql_fetch_assoc($qur)) {
    if (!$flag) {
        // display field/column names as first row
        $data.=implode("\t", array_keys($row)) . "\n";
        $flag = true;
    }
    $data.=implode("\t", array_values($row)) . "\n";
}
file_put_contents($filename, $data);
exit();
?>