【问题标题】:Export sqlite table using php使用php导出sqlite表
【发布时间】:2010-10-21 10:27:28
【问题描述】:

我刚刚开始使用 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";
?>

谁能帮我解决这个问题? 或者如果有更简单的方法会很棒。 干杯

【问题讨论】:

    标签: php sqlite pdo


    【解决方案1】:

    您正在将 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 数据库。

    【讨论】:

    • 嗨,谢谢。它需要是 PDO,因为它看起来像 sqlite_open 只支持 sqlie 2 而不是 3。我会去回复你!
    【解决方案2】:

    如果我需要以 CSV 文件的形式快速从 sqlite3 数据库中获取数据,我使用 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(选择语句的格式),将输出设置为名为 emails.csv 的文件,打开选择列标题(可选),选择所有emails 表中的数据,将输出设置为标准输出(关闭 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】:

      我已经改进了 Stacey 的答案,并认为我会在这里分享。 我添加了标题以使浏览器将输出下载为 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";
      }
      

      【讨论】:

        【解决方案4】:

        如果需要直接发送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);
            ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-05
          • 1970-01-01
          • 2016-04-10
          相关资源
          最近更新 更多