8

I have myssql db with different tables. The data between the tables are linked and I retrieve and display them by using the userid. I used the reference from PHP MYSQLi Displaying all tables in a database

But how do I export this information as a csv file? I have tried instead of echo changed it to a string and print the string to a csv file but it is not working.

I have also tried the example from: http://sudobash.net/php-export-mysql-query-to-csv-file/

But I can see the data but on top there is also junk (like "<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>"
etc) inside the csv file.

Is there another way to do this?

4

5 回答 5

15

如果要将每个 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..

还要确保检查您正在写入的目录的权限。

于 2013-05-06T04:39:00.513 回答
13

这是一个使用MySQLi 的 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;
}

这也是对不同答案的修改,其中建议了类似的解决方案,但标题部分对我不起作用,因此我更改了检索它们的方法。归功于@Jrgns

于 2013-08-06T03:30:55.627 回答
4

您可以尝试使用 MySqlINTO OUTFILE子句:

SELECT *
  INTO OUTFILE '/tmp/tablename.csv'
       FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
       LINES TERMINATED BY '\n'
   FROM tablename
  WHERE userid = 1
于 2013-05-06T05:00:15.570 回答
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);
于 2014-11-17T10:28:02.040 回答
1

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

这是一个与数据库连接的类,函数将使用 mysqli 和 PHP 做任何你想做的事情。在这种情况下,调用这个类(需要或包含),只需使用“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 打开文件。

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

于 2013-12-20T09:10:42.847 回答