MySQL 데이터베이스에 데이터가 있습니다.데이터를 CSV 파일로 출력하기 위한 URL을 사용자에게 보냅니다.
링크의 이메일, MySQL 쿼리 등을 취급하고 있습니다.
링크를 클릭하면 MySQL에서 레코드가 포함된 CVS를 다운로드하는 팝업이 뜨는 방법은 무엇입니까?
나는 이미 그 기록을 얻기 위한 모든 정보를 가지고 있다.PHP가 CSV 파일을 만들고 확장자가 .csv인 파일을 다운로드하도록 하는 방법을 모르겠습니다.
질문에 대한 답변
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") ));
시험:
header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0");
echo "record1,record2,record3n"; die;
기타
편집: CSV 필드를 선택적으로 인코딩하기 위해 사용하는 코드의 일부를 다음에 나타냅니다.
function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false
strpos($string, '"') !== false
strpos($string, "n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string; }
다음은 @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 파일에 링크하기만 하면 됩니다.이 파일은 다시 .csv 파일로 응답합니다.PHP 헤더가 그렇게 합니다.이를 통해 쿼리 문자열에 변수를 추가하고 출력을 커스터마이즈하는 등 쿨한 작업을 수행할 수 있습니다.
<a href="my_csv_creator.php?user=23&othervariable=true">Get CSV</a>
my_csv_displays.php는 쿼리 문자열에 지정된 변수와 함께 사용할 수 있습니다.예를 들어, 다른 데이터베이스 쿼리나 커스터마이즈된 데이터베이스 쿼리를 사용하거나 CSV의 컬럼을 변경하거나 파일 이름을 개인화하는 등의 작업을 할 수 있습니다.
User_John_Doe_10_Dec_11.csv