pre로 css처럼 찍어서 내보내는 php를 엑셀로 출력해서, 브라우져로부터 저장하게끔 하는 것을 chat gpt와 같이 php코딩을 하려고 합니다.
작성자 정보
- 삼둡 작성
 - 작성일
 
컨텐츠 정보
- 4,817 조회
 - 목록
 
본문
pre로 css처럼 찍어서 내보내는 php를 엑셀로 출력해서, 브라우져로부터 저장하게끔 하는 것을 chat gpt와 같이 php코딩을 하려고 합니다.
원본은 아래와 같아요
보안을 위해 **를 이용해서 몇가지는 지웠습니다.
<?php
include_once("./_common.php");
$g4[title] = "****cted";
include_once("./lib.php");
include_once("$g4[path]/_head.php");
erp_connect();
*****l(5);
$new_date=date("Y-m-d", $newdate);
$tmp_array = array();
  $tmp_array = $_POST[chk_serial];
echo "<pre>";
for ($xi=count($chk_serial)-1; $xi>=0; $xi--)
{
$query = "select * from ****** where serial={$chk_serial[$xi]};";
//echo $query,"<br>\n";
  $rs = mysql_query($query);
  $array = mysql_fetch_array($rs) ;
//print_r ($array);
$branch=$array[branch];
   $sql="select lifemaru, address, phone from branch where branch_name = '$branch'";
   $rs=sql_q2($sql);
   $row=mysql_fetch_array($rs);
   $lifemaru_mode=$row[0];
       $address=$row[1];
       $phone =$row[2];
   if ($lifemaru_mode == 2 || $lifemaru_mode == 1)
   {
       $branch="******(".$branch.")";
       }
       else
       {
       if ($branch="***")
               {
               $branch="*****";
               }
               else
               {
               $branch=$branch."*****";
               }
                }
       }
if (!$array[serial])
               {alert("*******");}
if (!$address and !$lifemaru_mode)
       {
       $address="*********호";
       }
echo
"$array[pt_name] , $array[phone1]  , $array[phone2] , $array[address] , $branch, $phone, $address,\n";
} //for xi route
mysql_close();
?>
 
<?php
include_once("./_common.php");
$g4['title'] = "송장출력 selected";
include_once("./lib.php");
include_once("$g4[path]/_head.php");
erp_connect();
rx_level(5);
$new_date = date("Y-m-d", $newdate);
$tmp_array = array();
$tmp_array = $_POST['chk_serial'];
$dataArray = array();
for ($xi = count($tmp_array) - 1; $xi >= 0; $xi--) {
   $query = "SELECT * FROM make_herb WHERE serial = {$tmp_array[$xi]};";
   $rs = mysql_query($query);
   $array = mysql_fetch_array($rs);
$branch = $array['branch'];
   $sql = "SELECT lifemaru, address, phone FROM branch WHERE branch_name = '$branch'";
   $rs = sql_q2($sql);
   $row = mysql_fetch_array($rs);
   $lifemaru_mode = $row[0];
   $address = $row[1];
   $phone = $row[2];
   if ($lifemaru_mode == 2 || $lifemaru_mode == 1) {
       $branch = "생명마루(" . $branch . ")";
   } else {
       if ($branch == "청담") {
           $branch = "청담BS한의원";
       } else {
           $branch = $branch . "한의원";
       }
   }
   if (!$array['serial']) {
       alert("처방이 유효하지 않습니다");
   }
   if (!$address && !$lifemaru_mode) {
       $address = "안산 단원구 고잔2길 65, 경신프라자 406호";
   }
   $dataArray[] = array(
       $array['pt_name'],
       $array['phone1'],
       $array['phone2'],
       $array['address'],
       $branch,
       $phone,
       $address
   );
}
// 엑셀 파일로 변환
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename=address_book.xls');
header('Cache-Control: max-age=0');
$output = fopen('php://output', 'w');
foreach ($dataArray as $row) {
   fputcsv($output, $row, "\t");
}
fclose($output);
// logging
$ip = $REMOTE_ADDR;
$action = $g4['title'] . $sql;
// logging ($member['mb_id'], $member['mb_name'], $ip, $action);
include_once("erp_tail.php");
mysql_connect("localhost", "intra", "pre00296") or die(mysql_error());
mysql_select_db("intra");
include_once("$g4[path]/_tail.php");
mysql_close();
?>
네가 준 코드로 하면, 이쁜 화면은 출력이 안되고 파일 저장만 되게 할 것 같은데, 안내화면은 출력되고 새 창이 열리면서 엑셀을 저장할 수 있게 수정해주라
ChatGPT
ChatGPT
알겠습니다. 아래 코드는 엑셀 파일 다운로드를 위한 버튼을 추가하고, 클릭 시 해당 데이터를 엑셀 파일로 변환하여 브라우저에 다운로드되도록 수정한 코드입니다. 이 코드는 버튼을 클릭하면 엑셀 다운로드 창이 뜨는 방식으로 동작합니다.
<!-- 엑셀 다운로드 버튼 추가 -->
<button onclick="downloadExcel()">엑셀 다운로드</button>
<script>
function downloadExcel() {
   var dataArray = <?php echo json_encode($dataArray); ?>;
   var csvContent = "data:text/csv;charset=utf-8,\uFEFF"; // BOM 추가
   dataArray.forEach(function(rowArray) {
       var row = rowArray.join("\t");
       csvContent += row + "\r\n";
   });
   var encodedUri = encodeURI(csvContent);
   var link = document.createElement("a");
   link.setAttribute("href", encodedUri);
   link.setAttribute("download", "address_book.xls");
   document.body.appendChild(link);
   link.click();
}
</script>
위에거 한글 문제로 폐기
------------------------
<a href="javascript:invoice_select();">
<span  style="background-color:#cc99cc;width:40px;text-align:center;">
<strong>송장css프린트</strong></span></a>
 
function invoice_select() {
   var f = document.fcategory;
   str = "송장css프린트";
   if (!check_confirm(str))
       return;
/*
   if (!confirm("선택한 항목에 "+str+"을 하시겠습니까?"))
       return;
*/
   f.action = "./invoice_css.php";
   f.submit();
}
 
preg_replace('/\r\n|\r|\n/',
아래 파일에서 버튼눌려지면 실행되어
csv출력을 시킵니다(다운로드 가능하게)
<?php
include_once("./_common.php");
$g4[title] = "송장출력 csv";
 
중간생략
$inputString= $array[address];
// '*'을 기준으로 문자열을 분할
$parts = explode('**', $inputString);
// '*' 이전의 문자열 추출 (str1)
$str1 = isset($parts[0]) ? $parts[0] : '';
// '*' 이후의 문자열 추출 (str2)
$str2 = isset($parts[1]) ? $parts[1] : '';
/*
echo
"$array[pt_name] ,$str1,  $array[phone1]  , $array[phone2] , 한약, ,  $branch, $phone, $address, $str2 , \n";
*/
   $dataArray[] = array(
       $array['pt_name'], $str1,
       $array['phone1'],
       $array['phone2'], '한약', '',
       $branch,
       $phone,
       $address, $str2 );
$pt_name = str_replace("," , ".", $array['pt_name']);
$str1 = str_replace(",",".", $str1);
$str1 = str_replace("\r"," ",$str1);
$phone1 = str_replace(",",".",$array['phone1']);
$phone2 = str_replace(",",".",$array['phone2']);
$branch = str_replace(",",".",$branch);
$phone = str_replace(",",".", $phone);
$address = str_replace(",",".",$address);
$str2 = str_replace(",",".",$str2);
$phone = str_replace("\n","", $phone);
$address = str_replace("\n","",$address);
$pt_name = preg_replace('/\r\n|\r|\n/','', $array['pt_name']);
$str1 = preg_replace('/\r\n|\r|\n/','',$str1);
$phone1 = preg_replace('/\r\n|\r|\n/','',$array['phone1']);
$phone2 = preg_replace('/\r\n|\r|\n/','',$array['phone2']);
$branch = preg_replace('/\r\n|\r|\n/','',$branch);
$phone = preg_replace('/\r\n|\r|\n/','', $phone);
$address = preg_replace('/\r\n|\r|\n/','',$address);
$str2 = preg_replace('/\r\n|\r|\n/','',$str2);
$phone = preg_replace('/\r\n|\r|\n/','', $phone);
$address = preg_replace('/\r\n|\r|\n/','',$address);
 
***콤마와 엔터때문에 추출하는 식이 많아지 ㅁ ㅜㅜ
$output =
       $array['pt_name'].",".
       $str1 .",".
       $array['phone1'].",".
       $array['phone2'].",".
       "한약,".
       " ,".
       $branch.",".
       $phone.",".
       $address.",". $str2 ."\r\n" ;
       print $output;
} //for xi route
mysql_close();
?>
 
관련자료
- 
			이전
 - 
			다음