美文网首页
【网页制作-php】一段将txt文本转换为html表格的php代

【网页制作-php】一段将txt文本转换为html表格的php代

作者: 爱睡的蟹老板 | 来源:发表于2019-02-16 13:09 被阅读0次
table2.txt中的内容如下: image.png

字段之间用空格符分开(这里对齐是为了好看,实际不需要对齐)

代码如下:

<head>

    <meta charset="utf-8">

    <meta http-equiv="x-ua-compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>生成HTML表格</title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">

    <link href="../css/bootstrap-theme.min.css" rel="stylesheet">

    <script src="../js/jquery.min.js" type="text/javascript"></script>

</head>

<?php

$filename = "table2.txt";

$myfile = fopen( $filename, "r" ) or die("Unable to open file!");

echo '<table class="table table-striped table-hover" style="width:500px">';

while(!feof($myfile)) {

    echo "<tr>";

    $row = fgets($myfile);

    //if(strlen($row) <2) continue;

    $hira_array = split(" +",$row);

    //$hira_array = split(" +|,",$row);

    foreach($hira_array as $hira){

        echo '<td>'.$hira.'</td>';

    }

    echo "</tr>";

}

echo "</table>";

fclose( $myfile );

?>

简单解释一下:

这里用到了bootstrap样式,所以先把bootstrap的库包含上,具体路径可以自己调整

    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/bootstrap-theme.min.css" rel="stylesheet">
    <script src="../js/jquery.min.js" type="text/javascript"></script>

打开文件并逐行读入

每读入一行时,在开头插入一个<tr>,结尾插入一个</tr>,刚好对应html table的一行。

对于每行的内容,使用php的字符串处理函数split()分开并保存到数组,其中 "+ " 是正则表达式,表示一个或多个空格。

数组中的每个元素的开头加上<td>,结尾加上</td>,刚好对应html table的一个元素

这就搞定了嗷!!

生成的html table如下: image.png

可以根据自己的喜好调整bootstrap table的样式,比如加上边框,只要在下面这行加一个table-bordered就好

echo '<table class="table table-striped table-hover table-bordered" style="width:500px">';
显示如下: image.png

更多教程可以访问(持续更新中):
http://www.bossqiao.com/menu/index.php?p=coding

相关文章

网友评论

      本文标题:【网页制作-php】一段将txt文本转换为html表格的php代

      本文链接:https://www.haomeiwen.com/subject/lcvbeqtx.html