1. 程式人生 > >php解析文字檔案呈現在表格上

php解析文字檔案呈現在表格上

name.txt如下

1 | 朱芳 | 18 | [email protected] | http://XEP.VC
2 | 康麗 | 22 | [email protected] | http://WSURR.PH
3 | 沈平 | 34 | [email protected] | http://BGEGFBTEP.KH
4 | 吳平 | 19 | [email protected] | http://FOQMVET.ST
5 | 邵濤 | 20 | [email protected] | http://JOQQ.TM
6 | 廖磊 | 14 | [email protected]

| http://XGDWPM.NET
7 | 文敏 | 12 | [email protected] | http://MUPT.SL
8 | 羅平 | 32 | [email protected] | http://ADEBOQ.BN
9 | 林芳 | 18 | [email protected] | http://NQXWELT.LC
10 | 黎超 | 39 | [email protected] | http://RFTTUKOK.RW

分析:

最終目標將.txt裡面的內容呈現在表格中

第一步:讀取檔案內容------------------->包含文字內容的字串資料

第二步:解析檔案中的內容------------->得到陣列

第三步通過混編的方式將資料呈現在表格

程式碼:

​
<?php 
//1.讀取檔案內容
$contents = file_get_contents('names.txt');

//2.按照一定的規則解析
//2.1 按照換行拆分,注意這裡要用雙引號,如果為單引號會將'\n'解析為轉義字元
  $lines =explode("\n",$contents);
  var_dump($lines);   //做完一步先小測試一下,看看是否有資料
//2.2 還要將上面得到的按豎線拆分
  foreach ($lines as $item) {
  	//因為最後一行是空格行,要處理空格行
  	if ($item=="") continue;

   // 1 | 朱芳 | 18 | 
[email protected]
| http://XEP.VC // |是我們不需要的,還要按豎線拆分 $cols =explode('|', $item); $data[]=$cols;//將每次得到的存放到一個數組中 } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>全部人員資訊表</title> </head> <body> <h1>全部人員資訊表</h1> <table> <thead> <tr> <th>編號</th> <th>姓名</th> <th>年齡</th> <th>郵箱</th> <th>網址</th> </tr> </thead> <tbody> <?php foreach ($data as $line): ?> //第一層遍歷上面的$data陣列 <tr> <?php foreach ($line as $col): ?>//第二層遍歷$data數組裡面的陣列 <?php $col=trim($col); ?> //由於得到的每個列,前後都有空格,先處理掉空格 <?php if(strpos($col, 'http://')===0): ?> //單獨處理最後一列, <td><a href="<?php echo strtolower($col); ?>"><?php echo substr($col, 7); ?></a></td> //將大寫轉化為小寫 <?php else: ?> <td><?php echo $col; ?><td>//其他按照普通輸出 <?php endif ?> <?php endforeach ?> </tr> <?php endforeach ?> </tbody> </table> </body> </html> ​

 

結果如圖: