将mysql导出到txt / xml文件并下载

时间:2011-12-15 21:10:25

标签: php mysql

我有一个显示一些mysql数据的表,每个条目都有一个复选框来选择单个条目,现在我希望能够将这些选定的条目导出到xml或txt文件中,我试过这个:

<?php
if ($_POST['exporttxt']) {
    for ($i = 0; $i < count($_POST['checkbox']); $i++) {
        $export_id = $checkbox[$i];

        $sql = "SELECT * FROM table WHERE id='$export_id'";
        $result = mysql_query($sql);
    }


    $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n";
    if ($result->num_rows > 0) {
        while ($myrow = $result->fetch_assoc())
        {
            $output .= "\t<row>\n";
            foreach ($myrow as $_name => $_value)
            {
                $output .= "\t\t<$_name>$_value</$_name>\n";
            }
            $output .= "\t</row>\n";
        }
    }
    $output .= "</root>";
}

header('content-type: text/xml');
header('content-disposition: attachment; filename=data_export.xml');
echo $output;
exit;

?>

但那根本不起作用,有什么提示吗?

我已经改变了一些代码,我现在正在使用这个

<?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
   $export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM ticket WHERE id='$export_id'");
$text = mysql_fetch_assoc($text);
$text = $text["code"];

ob_end_flush();
header("Content-type: text/plain");
header("Content-disposition: attachment;filename=\"filename.txt\"");
   header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    header("Content-Length: ".strlen($output).";\n");



echo($text);


}
}


?>

我现在在屏幕上输出正确的输出,但它不能让我下载文件?

2 个答案:

答案 0 :(得分:1)

您的原始代码分别查询每个已复选的ID(这是一种漫长而费力的处理方式),并试图逐行转储结果(不适合您)。

试试这个。 (注意:未经测试,但应该为您提供良好的发展起点。

if( $_POST['exporttxt'] ){

  if( count( $_POST['checkbox'] )>0 ){

    // If the checkbox values are meant to all be integers, you might want to perform some validation/sanitisation/filtering here
    // Up to you to do that

    // Collapse the IDs from the checkboxes into a comma-delimited string
    $export_ids = implode( ',' , $_POST['checkbox'] );

    // Template the SQL Query
    $sqlTpl = 'SELECT code FROM ticket WHERE id IN ( %s )';
    // Compile the SQL Query String
    $sqlStr = sprintf( $sqlTpl , $export_ids );

    // Execute the SQL Query
    if( !( $sqlRes = mysql_query( $sqlStr ) ) ){
      // SQL Error - Log it, Handle it
    }elseif( mysql_num_rows( $sqlRes )==0) {
      // No Rows Returned - Log it, Handle it
    }else{
      // We have results - process them
      $text = array();
      while( $r = mysql_fetch_assoc( $sqlRes ) ){
        // Looping through the returned rows, adding them to the $text array
        $text[] = $r['code'];
      }
      // Collapse the $text array down into a normal string, with one element per line
      $output = implode( "\n" , $text );

      // Output Handling from @narcisradu's answer
      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Cache-Control: private",false);
      header("Content-Transfer-Encoding: binary;\n");
      header("Content-Disposition: attachment; filename=\"filename.txt\";\n");
      header("Content-Type: application/force-download");
      header("Content-Type: application/octet-stream");
      header("Content-Type: application/download");
      header("Content-Description: File Transfer");
      header("Content-Length: ".strlen($output).";\n");
      echo $output;

      die; // Prevent any further output
    }

  }else{
    // No Checkboxes Checked
    echo 'You must select one or more checkboxes to export something, muppet.';
  }

}

答案 1 :(得分:0)

首先:

for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];

$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);}

这段代码实际上会对_POST ['checkbox']数组中的每个元素进行查询,但是你使用的是最后一个查询的结果,而不是解析每个查询的结果。

请通过直接在浏览器中显示,确保生成的XML格式正确,并确实有一些数据。

之后你可能会尝试下载:

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Transfer-Encoding: binary;\n");
    header("Content-Disposition: attachment; filename=\"".urlencode(basename($file_name))."\";\n");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    header("Content-Length: ".strlen($output).";\n");
    ob_end_flush();