:::

8. CSV的匯出與匯入

一、匯出文字檔

1.匯出文字檔的作法其實很簡單,您只要在程式裡加入以下的程式碼就行了:
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=檔名");
echo 主要內容;
exit;

2.檔案格式如下:
CSV檔:text/x-csv
sxw檔:application/octet-stream
word檔:application/msword
excel檔:application/vnd.ms-excel

二、匯入文字檔上傳介面:

<form action='接收檔.php' method='post' enctype='multipart/form-data'>
<INPUT type='file' name='userfile'>
<INPUT type='hidden' name='op' value='import'>
<INPUT type='submit' value='匯入'>
</form>

三、匯入文字檔:

//開啟上傳檔
$handle = fopen($_FILES['userfile']['tmp_name'], "r") or die("無法開啟");

//利用fgetcsv()來讀取內容
while (($data = fgetcsv($handle, 1000)) !== FALSE) {
  $sql="insert into calender (`date`,`event`) values ('{$data[0]}','{$data[1]}')";
    mysql_query($sql) or die($sql);
}

//關閉上傳檔
fclose($handle);

1.控制符=fopen(檔名,模式):打開檔案
2.布林值=fclose(檔案控制符):關閉檔案
3.陣列=fgetcsv(檔案控制符,[最長讀取長度],[分格符號],[文字引號]):讀取CSV檔

四、文字檔轉碼:

1.由於Excel僅能編輯Big5的中文編碼,故若是您希望會出的檔案可以讓Excel開啟,匯出時,記得將編碼轉為Big5。
(1) iconv  ( "舊編碼"  , "新編碼"  , "原文" );
echo iconv( "UTF-8", "Big5" , $main);
(2) mb_convert_encoding( "原文" , "新編碼" , "舊編碼");
echo mb_convert_encoding($main , "Big5" , "UTF-8");

五、建立RSS:

(1) 在首頁加入:<link rel="alternate" type="application/rss+xml" title="" href="rss.php" />
(2) 製作RSS結構,RSS為一個簡單的XML檔,因此,rss.php只要能輸出RSS規定的XML架構(請參考rss.php檔)即可。

<?xml version="1.0" encoding="編碼" ?>
<rss version="2.0">

<channel>
  <title>網站名稱</title>
  <link>網站網址</link>
  <description>網站簡介</description>
  <lastBuildDate>最後更新日期</lastBuildDate>
 
  <item>
    <title>事件名稱</title>
    <link>連結網址</link>
    <pubDate>事件日期</pubDate>
    <description>事件內容</description>
  </item>
 
</channel>
</rss>


:::

搜尋

QR Code 區塊

https%3A%2F%2Fwww.tad0616.net%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D8%26tbdsn%3D202

書籍目錄

展開 | 闔起

線上使用者

152人線上 (7人在瀏覽線上書籍)

會員: 0

訪客: 152

更多…