PHP – Read CSV File & cover to HTML Table

Loading

要如何透過 PHP 來讀取 Linux 下 CSV (每筆資料用 “,” 做區分) 檔案並把它轉成為 HTML Table.

測試環境為 CentOS 7 虛擬機 (IP: http://192.168.95.205) , Apache 安裝設定請參考 https://benjr.tw/323 , 如果使用 Nginx (Web server) 請參考 – https://benjr.tw/95761 與 PHP-FPM – https://benjr.tw/95767

使用 Ubuntu 16.04 x86_64 設定 Apache2 請參考 https://benjr.tw/95861 , web server 為 Nginx 請參考 https://benjr.tw/96633 .

csv 檔案使用 dstat 的 output 檔案,關於 Linux command dstat 請參考 – https://benjr.tw/93514

[root@localhost html]# cat dstat.csv
"Dstat 0.7.2 CSV output"
"Author:","Dag Wieers <dag@wieers.com>",,,,"URL:","http://dag.wieers.com/home-made/dstat/"
"Host:","ubuntu",,,,"User:","root"
"Cmdline:","dstat -n -N eth0,eth1 --output /tmp/output.csv",,,,"Date:","12 Jan 2015 00:43:13 PST"
 
"net/eth0",,"net/eth1",
"recv","send","recv","send"
0.0,0.0,0.0,0.0
180.0,180.0,0.0,0.0
120.0,120.0,0.0,0.0
120.0,120.0,0.0,0.0
275.0,215.0,0.0,0.0

範例 一

[root@localhost html]# cat csvtable.php 
<html>
<head>
  <title>Table Sample</title>
</head>
<body>
<table>
<?php
$file = fopen("dstat.csv","r") or die("Unable to open file!");
while(($row = fgets($file)) != false) {
  echo "<tr>";
  $col = explode(',',$row);
  foreach($col as $data) {
     echo "<td>". trim($data)."</td>";
  }
  echo "</tr>";
  }
fclose($file)
?>
</table>
</body>
</html>

執行結果(圖示):

PHP 函數說明:

  • fopen() – Opens file or URL
    fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource
  • or die() – or 的用法跟 Linux bash script 的 cmd1 || cmd2 一樣 ,若 cmd1 執行正確且無錯誤,則 cmd2 不執行 ,反之若 cmd1 執行完畢且為錯誤,則開始執行 cmd2.
    會有下列的兩種情況.
    若 fopen(“test.txt”, “r”) 執行正確且無錯誤就結束.
    若 fopen(“test.txt”, “r”) 執行失敗就執行 die(“Unable to open file!”) (die 等同 exit – http://php.net/manual/en/aliases.php )- 顯示訊息並跳出程式.
  • fgets() – Gets a line from file pointer
    fgets ( resource $handle [, int $length ] ) : string
  • explode() — Split a string by a string
    explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array
  • foreach() – The foreach construct provides an easy way to iterate over arrays.
    foreach (array_expression as $value) , foreach (array_expression as $key => $value)
  • trim() — Strip whitespace (or other characters) from the beginning and end of a string
    trim ( string $str [, string $character_mask = ” \t\n\r\0\x0B” ] ) : string
  • fclose() – Closes an open file pointer
    close ( resource $handle ) : bool

老實說這樣的輸出格式根本看不出來有沒有 html table,可以透過 https://divtable.com/table-styler/ 來選擇並自動產生 table 的 css 檔案.

[root@localhost html]# cat table.css 
table.blueTable {
  border: 1px solid #1C6EA4;
  background-color: #EEEEEE;
  width: 100%;
  text-align: left;
  border-collapse: collapse;
}
table.blueTable td, table.blueTable th {
  border: 1px solid #AAAAAA;
  padding: 3px 2px;
}
table.blueTable tbody td {
  font-size: 13px;
}
table.blueTable tr:nth-child(even) {
  background: #D0E4F5;
}
table.blueTable thead {
  background: #1C6EA4;
  background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
  background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
  background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
  border-bottom: 2px solid #444444;
}
table.blueTable thead th {
  font-size: 15px;
  font-weight: bold;
  color: #FFFFFF;
  border-left: 2px solid #D0E4F5;
}
table.blueTable thead th:first-child {
  border-left: none;
}

table.blueTable tfoot {
  font-size: 14px;
  font-weight: bold;
  color: #FFFFFF;
  background: #D0E4F5;
  background: -moz-linear-gradient(top, #dcebf7 0%, #d4e6f6 66%, #D0E4F5 100%);
  background: -webkit-linear-gradient(top, #dcebf7 0%, #d4e6f6 66%, #D0E4F5 100%);
  background: linear-gradient(to bottom, #dcebf7 0%, #d4e6f6 66%, #D0E4F5 100%);
  border-top: 2px solid #444444;
}
table.blueTable tfoot td {
  font-size: 14px;
}
table.blueTable tfoot .links {
  text-align: right;
}
table.blueTable tfoot .links a{
  display: inline-block;
  background: #1C6EA4;
  color: #FFFFFF;
  padding: 2px 8px;
  border-radius: 5px;
}

主要在 <head> 加入 <link rel=”stylesheet” href=”table.css”> 並定義 table 所使用的 css <table class=blueTable>

[root@localhost html]# cat csvtable1.php 
<html>
<head>
  <title>Table Sample</title>
  <link rel="stylesheet" href="table.css">
</head>
<body>
<table class=blueTable>
<?php
$file = fopen("dstat.csv","r") or die("Unable to open file!");
while(($row = fgets($file)) != false) {
  echo "<tr>";
  $col = explode(',',$row);
  foreach($col as $data) {
     echo "<td>". trim($data)."</td>";
  }
  echo "</tr>";
  }
fclose($file)
?>
</table>
</body>
</html>

執行結果(圖示):

範例 二

與範例 一的差別為部分使用的函數不同.

[root@localhost html]# cat csvtable2.php 
<html>
<head>
  <title>Table Sample</title>
  <link rel="stylesheet" href="table.css">
</head>
<body>
<table class="blueTable">
<?php
$file = fopen("dstat.csv","r") or die("Unable to open file!");
while (($line = fgetcsv($file)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($file);
?>
</table>
</body>
</html>

執行結果(圖示):

PHP 函數說明:

  • fopen() – Opens file or URL
    fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource
  • or die() – or 的用法跟 Linux bash script 的 cmd1 || cmd2 一樣 ,若 cmd1 執行正確且無錯誤,則 cmd2 不執行 ,反之若 cmd1 執行完畢且為錯誤,則開始執行 cmd2.
    會有下列的兩種情況.
    若 fopen(“test.txt”, “r”) 執行正確且無錯誤就結束.
    若 fopen(“test.txt”, “r”) 執行失敗就執行 die(“Unable to open file!”) (die 等同 exit – http://php.net/manual/en/aliases.php )- 顯示訊息並跳出程式.
  • fgetcsv() – Gets line from file pointer and parse for CSV fields
    fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = “,” [, string $enclosure = ‘”‘ [, string $escape = “\\” ]]]] ) : array
  • foreach() – The foreach construct provides an easy way to iterate over arrays.
    foreach (array_expression as $value) , foreach (array_expression as $key => $value)
  • htmlspecialchars() – Convert special characters to HTML entities
    htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get(“default_charset”) [, bool $double_encode = TRUE ]]] ) : string
  • fclose() – Closes an open file pointer
    close ( resource $handle ) : bool
沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料