在PHP中查询mysql并将数据导出为CSV

时间:2013-05-06 03:19:32

标签: php mysql csv

我有不同表的myssql db。表之间的数据是链接的,我使用userid检索并显示它们。我使用了PHP MYSQLi Displaying all tables in a database

中的引用

但是如何将此信息导出为csv文件?我试过而不是echo将其更改为字符串并将字符串打印到csv文件但它无法正常工作。

我也试过这个例子: http://sudobash.net/php-export-mysql-query-to-csv-file/

但我可以看到数据,但最重要的还有垃圾(如"<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>")  等)在csv文件中。

还有其他办法吗?

5 个答案:

答案 0 :(得分:14)

如果要将每个MySQL行写入CSV文件,可以使用内置的PHP5函数fputcsv

$result = mysqli_query($con, 'SELECT * FROM table');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

$fp = fopen('file.csv', 'w');

foreach ($row as $val) {
    fputcsv($fp, $val);
}

fclose($fp);

对于写入file.csv的每一行,应该返回逗号分隔的字符串:

row1 val1, row1 val2
row2 val1, row2 val2 
etc..

另外,请务必检查您要写入的目录的权限。

答案 1 :(得分:12)

这是一个使用MySQLi's fetch_fields函数合并标题或字段名称的解决方案 -

$query = "SELECT * FROM table";
$result = $db->query($query);
if (!$result) die('Couldn\'t fetch records');
$headers = $result->fetch_fields();
foreach($headers as $header) {
    $head[] = $header->name;
}
$fp = fopen('php://output', 'w');

if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, array_values($head)); 
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

这也是一个修改of a different answer,其中提出了类似的解决方案,但标题部分对我不起作用,所以我改变了检索它们的方法。归功于@Jrgns

答案 2 :(得分:4)

您可以尝试使用MySql INTO OUTFILE子句:

SELECT *
  INTO OUTFILE '/tmp/tablename.csv'
       FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
       LINES TERMINATED BY '\n'
   FROM tablename
  WHERE userid = 1

答案 3 :(得分:1)

用于从mysqli查询创建和下载csv文件(使用面向对象)我认为这会有所帮助。

这是一个与数据库连接的类,函数将使用mysqli和PHP执行任何操作。在这种情况下,调用此类(require或include),只需使用“downloadCsv()”函数。

例如,这将是“class.php”文件:

<?php
class DB{

private $con;

//this constructor connects with the database
public function __construct(){
$this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName");

if($this->con->connect_errno > 0){
    die('There was a problem [' . $con->connect_error . ']');
    }
}

//create the function that will download a csv file from a mysqli query

public function downloadCsv(){

$count = 0;
$header = "";
$data = "";
//query
$result = $this->con->query("SELECT * FROM Your_TableName");
//count fields
$count = $result->field_count;
//columns names
$names = $result->fetch_fields();
//put column names into header
foreach($names as $value) {
    $header .= $value->name.";";
    }
}
//put rows from your query
while($row = $result->fetch_row())  {
    $line = '';
    foreach($row as $value)       {
        if(!isset($value) || $value == "")  {
            $value = ";"; //in this case, ";" separates columns
    } else {
            $value = str_replace('"', '""', $value);
            $value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too
        }
        $line .= $value;
    } //end foreach
    $data .= trim($line)."\n";
} //end while
//avoiding problems with data that includes "\r"
$data = str_replace("\r", "", $data);
//if empty query
if ($data == "") {
    $data = "\nno matching records found\n";
}
$count = $result->field_count;

//Download csv file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=FILENAME.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $header."\n".$data."\n";

}
?>

创建“class.php”文件后,在本例中,在“download.php”文件中使用该函数:

<?php
//call the "class.php" file
require_once 'class.php';
//instantiate DB class
$export = new DB();
//call function
$export->downloadCsv();
?>

下载后,使用MS Excel打开文件。

我希望这对你有帮助,我想我写的很好,我对文字和代码字段感到不舒服。

答案 4 :(得分:1)

试试这个。

function addRowToCsv(& $csvString, $cols) {
    $csvString .= implode(',', $cols) . PHP_EOL; //Edits must be 6 characters - all I added was a "." before the =. :-)
}

$csvString = '';
$first = true;

while ($row = mysqli_fetch_assoc($query)) {
    if ($first === true) {
        $first = false;
        addRowToCsv($csvString, array_keys($row));
    }
    addRowToCsv($csvString, $row);
}

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');

echo $csvString;

请注意,addRowToCsv的第一个参数是通过引用传递的。这不是必需的,您可以轻松使用返回值,但这就是我要做的。

如果您想将输出保存到文件而不是将其作为下载服务,请使用上面的内容但替换

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');

echo $csvString;

使用..

file_put_contents('MyCsvFile.csv', $csvString);