문제

MySQL 데이터베이스에 데이터가 있습니다. CSV 파일로 데이터를 가져 오기 위해 사용자에게 URL을 보내고 있습니다.

링크, MySQL 쿼리 등의 이메일이 있습니다.

링크를 클릭하면 MySQL의 레코드와 함께 CVS를 다운로드하기 위해 팝업을 할 수있는 방법은 무엇입니까?

이미 레코드를 얻을 수있는 모든 정보가 있습니다. PHP가 CSV 파일을 만들고 .csv 확장자가있는 파일을 다운로드하는 방법을 알지 못합니다.

도움이 되었습니까?

해결책

노력하다:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
die;

편집 : 다음은 CSV 필드를 선택적으로 인코딩하는 데 사용하는 코드 스 니펫입니다.

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}

다른 팁

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function outputCSV($data) {
  $output = fopen("php://output", "wb");
  foreach ($data as $row)
    fputcsv($output, $row); // here you can change delimiter/enclosure
  fclose($output);
}

outputCSV(array(
  array("name 1", "age 1", "city 1"),
  array("name 2", "age 2", "city 2"),
  array("name 3", "age 3", "city 3")
));

php : // 출력
fputcsv

다음은 @andrew가 게시 한 php.net의 기능의 개선 된 버전입니다.

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

사용하기 쉽고 MySQL (I)/PDO 결과 세트와 잘 작동합니다.

download_csv_results($results, 'your_name_here.csv');

기억해 exit() 페이지를 완료하면 전화를 한 후.

이미 이미 말한 것 외에도 다음을 추가해야 할 수도 있습니다.

header("Content-Transfer-Encoding: UTF-8");

사람들의 이름이나 도시와 같이 여러 언어가있는 파일을 처리 할 때 매우 유용합니다.

실은 조금 오래되었지만, 미래의 참조와 멍청한 사람은 다음과 같습니다.

여기있는 다른 모든 사람들은 CSV를 만드는 방법을 설명하지만 질문의 기본 부분을 놓치는 방법을 놓치는 방법입니다. CSV 파일 다운로드에 연결하려면 .php-file에 연결하여 .CSV 파일로 응답합니다. PHP 헤더가 그렇게합니다. 이렇게하면 쿼리 스트링에 변수를 추가하고 출력을 사용자 정의하는 것과 같은 멋진 제품이 가능합니다.

<a href="my_csv_creator.php?user=23&amp;othervariable=true">Get CSV</a>

my_csv_creator.php는 QueryString에 주어진 변수와 함께 작동 할 수 있으며 예를 들어 다른 또는 사용자 정의 된 데이터베이스 쿼리를 사용하고 CSV의 열을 변경하고 파일 이름을 개인화하는 등 : on :

User_John_Doe_10_Dec_11.csv

파일을 작성한 다음 올바른 헤더로 참조를 반환하여 저장을 트리거하여 다음을 필요에 따라 다음을 편집하십시오. CSV 데이터를 $ CSVDATA에 넣으십시오.

$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);

header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);

다음은 PDO를 사용하여 열 헤더를 포함하는 전체 작업 예입니다.

$query = $pdo->prepare('SELECT * FROM test WHERE id=?');
$query->execute(array($id));    
$results = $query->fetchAll(PDO::FETCH_ASSOC);
download_csv_results($results, 'test.csv'); 
exit();


function download_csv_results($results, $name)
{            
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");    
    fputcsv($outstream, array_keys($results[0]));

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

먼저 구분 기자로 쉼표가있는 문자열로 데이터를 만듭니다 ( ","). 이 같은

$CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine

$rand = rand(1,50); //Make a random int number between 1 to 50.
$file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server 
                                     //side it is recommended that the file name be different.

file_put_contents($file,$CSV_string);

/* Or try this code if $CSV_string is an array
    fh =fopen($file, 'w');
    fputcsv($fh , $CSV_string , ","  , "\n" ); // "," is delimiter // "\n" is new line.
    fclose($fh);
*/

이봐 아주 잘 작동합니다 .... !!!! Peter Mortensen과 Connor Burton에게 감사드립니다

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

간단한 방법 -

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('data.csv', 'wb');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

그래서 각 줄 $data 배열은 새로 생성 된 CSV 파일의 새로운 라인으로 이동합니다. PHP 5 이후에만 작동합니다.

단순히 데이터를 CSV 사용으로 작성할 수 있습니다 fputcsv 기능. 아래 예제를 살펴 보겠습니다. 목록 배열을 CSV 파일에 쓰십시오

$list[] = array("Cars", "Planes", "Ships");
$list[] = array("Car's2", "Planes2", "Ships2");
//define headers for CSV 
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file_name.csv');
//write data into CSV
$fp = fopen('php://output', 'wb');
//convert data to UTF-8 
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($list as $line) {
    fputcsv($fp, $line);
}
fclose($fp);

가장 쉬운 방법은 전용을 사용하는 것입니다 CSV 클래스 이와 같이:

$csv = new csv();
$csv->load_data(array(
    array('name'=>'John', 'age'=>35),
    array('name'=>'Adrian', 'age'=>23), 
    array('name'=>'William', 'age'=>57) 
));
$csv->send_file('age.csv'); 

대신에:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

사용:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}

이미 아주 좋은 솔루션이 왔습니다. 초보자가 총 도움을 받도록 총 코드를 넣고 있습니다.

<?php
extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$table.csv");
header("Pragma: no-cache");
header("Expires: 0");

require_once("includes/functions.php"); //necessary mysql connection functions here

//first of all I'll get the column name to put title of csv file.
$query = "SHOW columns FROM $table";
$headers = mysql_query($query) or die(mysql_error());
$csv_head = array();
while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
{
    $csv_head[] =  $row['Field'];
}
echo implode(",", $csv_head)."\n";

//now I'll bring the data.
$query = "SELECT * FROM $table";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    foreach ($row as $key => $value) {
            //there may be separator (here I have used comma) inside data. So need to put double quote around such data.
        if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
            $row[$key] = '"' . str_replace('"', '""', $value) . '"';
        }
    }
    echo implode(",", $row)."\n";
}

?>

이 코드를 csv download.php에 저장했습니다

이제이 데이터를 사용하여 CSV 파일을 다운로드 한 방법을 확인하십시오.

<a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>

따라서 링크를 클릭하면 브라우저에서 CSV-Download.php 페이지로 가져 가지 않고 파일을 다운로드합니다.

CSV로 보내고 파일 이름을 제공하도록하려면 Header ()를 사용하십시오.

http://us2.php.net/header

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

CSV 자체를 만드는 한, 다른 콘텐츠와 마찬가지로 결과 세트를 통해 루프를 통해 출력을 형식화하고 전송합니다.

자신의 CSV 코드를 작성하는 것은 아마도 시간 낭비 일 것입니다. 리그 / CSV와 같은 패키지를 사용합니다. 그것은 당신을위한 모든 어려운 것들을 다루고, 문서는 훌륭하고 매우 안정적인 / 신뢰할 수 있습니다.

http://csv.thephpleague.com/

작곡가를 사용해야합니다. 작곡가가 무엇인지 모르면 강력히 살펴 보는 것이 좋습니다. https://getcomposer.org/

<?
    // Connect to database
    $result = mysql_query("select id
    from tablename
    where shid=3");
    list($DBshid) = mysql_fetch_row($result);

    /***********************************
    Write date to CSV file
    ***********************************/

    $_file = 'show.csv';
    $_fp = @fopen( $_file, 'wb' );

    $result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");

    while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
    {
        $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
        @fwrite( $_fp, $_csv_data);
    }
    @fclose( $_fp );
?>

PHP 스크립트를 사용하여 CSV 파일로 작성하는 방법은 무엇입니까? 실제로 나도 그것을 찾고있었습니다. PHP에서는 쉬운 일입니다. fputs (handler, content) -이 기능은 나에게 효율적으로 작동합니다. 먼저 fopen ($ csvfilename, 'wb')을 사용하여 컨텐츠를 작성 해야하는 파일을 열어야합니다.

$CSVFileName = “test.csv”;
$fp = fopen($CSVFileName, ‘wb’);

//Multiple iterations to append the data using function fputs()
foreach ($csv_post as $temp)
{
    $line = “”;
    $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
    $line .= “\n”;
    fputs($fp, $line);
}

다음은 특정 날짜 사이에 데이터를 가져 와서 이전에 수행 한 것입니다. 도움이되기를 바랍니다.

<?php
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    ini_set('display_errors',1);
    $private=1;
    error_reporting(E_ALL ^ E_NOTICE);

    mysql_connect("localhost", "user", "pass") or die(mysql_error());
    mysql_select_db("db") or die(mysql_error());

    $start = mysql_real_escape_string($_GET["start"]);
    $end = mysql_real_escape_string($_GET["end"]);

    $query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
    $select_c = mysql_query($query) or die(mysql_error());

    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        $result.="{$row['email']},";
        $result.="\n";
        echo $result;
    }
?>

입력하십시오 $output CSV 데이터를 변수 및 올바른 헤더로 에코

header("Content-type: application/download\r\n");
header("Content-disposition: filename=filename.csv\r\n\r\n");
header("Content-Transfer-Encoding: ASCII\r\n");
header("Content-length: ".strlen($output)."\r\n");
echo $output;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top