使用php导出sqlite表

时间:2010-10-21 10:27:28

标签: php sqlite pdo

我刚刚开始使用PHP,我需要将我的sqlite数据库中的表导出为CSV或理想的XLS。我找到了一个使用mysql的例子,但是我无法将其转换为使用sqlite。

这是我到目前为止所拥有的:

<?php
$db     = new PDO('sqlite:../ccm.sqlite');
$query  = $db->query('SELECT * FROM Emails');
$export = sqlite_query ($query);
$fields = sqlite_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ ){
    $header .= sqlite_field_name( $export , $i ) . "\t";
}

while( $row = sqlite_fetch_row( $export ) ){
//sqlite_fetch_row doesnt actually exist...
    $line = '';
    foreach( $row as $value ){                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) ){
            $value = "\t";
        }else{
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" ){
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=emails.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>

任何人都可以帮我解决这个问题吗? 或者如果有一种更简单的方法会很棒。 干杯

4 个答案:

答案 0 :(得分:2)

您正在将PDO方法与sqlite_ *函数混合使用;尝试使用其中一个:

$db = new PDO("sqlite:../ccm.sqlite");
$query = $db->query("select * from emails");
$first_row = true;
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
  if ($first_row)
  {
    // I'm not sure how to get the field names using a PDO method but
    // we can use the first row's (or any row's) key values as these
    // are the field names.
    $first_row = false;
    $number_of_fields = count($row);
    $field_names = array_keys($row);
    $first_field_name = $field_names[0];
  }
  // do stuff here with the row
  print_r($row);
}

$db = sqlite_open("../cmm.sqlite");
$query = sqlite_query($db, "select * from emails");
$number_of_fields = sqlite_num_fields($query);
$first_field_name = sqlite_field_name($query, 0);
while ($row = sqlite_fetch_array($query))
{
    // do stuff here with the row.
    print_r($row);
}

我不是100%肯定,但我认为PDO适用于sqlite3数据库,而sqlite_ *函数适用于sqlite2数据库。

答案 1 :(得分:2)

我对斯泰西的回答有所改进,并认为我会在这里分享。 我添加了标题以使浏览器将输出下载为CSV文件。

<?
// Set headers to make the browser download the results as a csv file
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=filename.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Connect to DB
$conn = new PDO('sqlite:db_name.db');

// Query
$query = $conn->query("SELECT * FROM some_table");

// Fetch the first row
$row = $query->fetch(PDO::FETCH_ASSOC);

// If no results are found, echo a message and stop
if ($row == false){
    echo "No results";
    exit;
}

// Print the titles using the first line
print_titles($row);
// Iterate over the results and print each one in a line
while ($row != false) {
    // Print the line
  echo implode(array_values($row), ",") . "\n";
    // Fetch the next line
  $row = $query->fetch(PDO::FETCH_ASSOC);
}

// Prints the column names
function print_titles($row){
    echo implode(array_keys($row), ",") . "\n";
}

答案 2 :(得分:1)

如果我需要快速从sqlite3数据库中获取数据作为CSV文件,我使用sqlite3 CLI:

$ sqlite3 ccm.sqlite
sqlite> .mode csv
sqlite> .output emails.csv
sqlite> .headers on
sqlite> select * from emails
sqlite> .output stdout
sqlite> .quit
$ cat emails.csv

这将启动sqlite3 CLI打开ccm.sqlite数据库,将输出模式设置为csv(select语句的格式),将输出设置为名为emails.csv的文件,打开选择列标题(可选),全选电子邮件表中的数据,将输出设置为标准输出(关闭emails.csv文件),退出CLI并通过将输出发送到标准输出来检查输出。

您可以输出其他格式,在sqlite3 CLI提示符下键入.help:

.mode MODE ?TABLE?     Set output mode where MODE is one of:
                         csv      Comma-separated values
                         column   Left-aligned columns.  (See .width)
                         html     HTML <table> code
                         insert   SQL insert statements for TABLE
                         line     One value per line
                         list     Values delimited by .separator string
                         tabs     Tab-separated values
                         tcl      TCL list elements

答案 3 :(得分:1)

如果您需要将CSV文件直接发送到浏览器,而无需写入外部文件,则可以打开输出并在其上使用fputcsv。

    <?php
    $out = fopen('php://output', 'w');
// print column header
    fputcsv($out, array_keys($row)));
//or print content directly
    fputcsv($out, array_values($row)));
    fclose($out);
    ?>