【问题标题】:Is there a way to import text data from a text file into a html table [duplicate]有没有办法将文本数据从文本文件导入到 html 表中[重复]
【发布时间】:2019-09-07 03:37:32
【问题描述】:

我必须将文本文件加载到 HTML 表格中,但不知道该怎么做。

这是我必须放入表格的文档和文本文档的示例。

<?php # Script 3.4 - index.php
$page_title = 'Climate Data For All Cities';
include ('./includes/header.html');
?>
<h1 id="mainhead">Climate Data For All Cities</h1>
<p>There are currently 80 cities.</p>
(table will go here)
<?php
include ('./includes/footer.html');
?>

文本文档:

Lander  WY  5557    99  -35 109 140 67
Milwaukee   WI  672 98  -7  79  177 124
Seattle WA  400 94  12  55  233 163
Spokane WA  2356    98  -16 95  187 112
Burlington  VT  332 91  6   54  217 168
Norfolk VA  24  98  19  85  145 117
Richmond    VA  164 101 16  105 165 115
Salt Lake City  UT  4221    103 -11 129 152 86
Dallas  TX  551 106 10  130 152 89
Houston TX  96  104 19  73  166 94
San Antonio TX  788 102 16  90  165 83
Memphis TN  258 101 12  121 151 112
Huron   SD  1281    100 -30 121 147 80
Rapid City  SD  3162    106 -30 106 127 95

【问题讨论】:

标签: php html


【解决方案1】:

我更像是一个 JS 类型的人,但您可以将其集成到 PHP 中以无缝工作。您需要将以下内容添加到您的头部标签中

  <script
    src="https://code.jquery.com/jquery-3.4.0.min.js"
    integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="
    crossorigin="anonymous">
  </script>
  <script src="text.js" charset="utf-8"></script>

您提供的文本文件保存为与 index html 同级的“text.txt”,以及以下 text.js 脚本。

text.txt 包含以下内容

Lander  WY  5557    99  -35 109 140 67
Milwaukee   WI  672 98  -7  79  177 124
Seattle WA  400 94  12  55  233 163
Spokane WA  2356    98  -16 95  187 112
Burlington  VT  332 91  6   54  217 168
Norfolk VA  24  98  19  85  145 117
Richmond    VA  164 101 16  105 165 115
Salt Lake City  UT  4221    103 -11 129 152 86
Dallas  TX  551 106 10  130 152 89
Houston TX  96  104 19  73  166 94
San Antonio TX  788 102 16  90  165 83
Memphis TN  258 101 12  121 151 112
Huron   SD  1281    100 -30 121 147 80
Rapid City  SD  3162    106 -30 106 127 95

您的正文中应该有以下 HTML(可以在 php 中完成)

<h1>Text File reader</h1>
<button type="button" name="button" id="fileReadButton">LOAD</button>
<table id="textFileContentTable">
  <thead>
    <th>Location</th>
    <th>State</th>
    <th>High</th>
    <th>Low</th>
    <th>Days Clear</th>
    <th>Days Cloudy</th>
    <th>Days with Precip</th>
    <th>Days With Snow</th>
  </thead>
</table>

最后,这里是通过单击按钮从文本文件中获取数据并填写表格的脚本。

$().ready(function(){
 function populateTable(filePath){
    // get request for the file
    $.get(filePath, function(response){
      let rows = response.split("\n");
      // getting each row of the text file
      for(var i = 0; i < rows.length; i++){
        var validRowData = [];
        var rowData = rows[i].split(" ");
        // getting the data for the row
        for (var z = 0; z < rowData.length; z++) {
          if(rowData[z] == ""){
          }else{
            validRowData.push(rowData[z]);
          }
          // sanitising the strings like San Antonio and Rapid City
          if(validRowData.length == 9){
            validRowData[0] = validRowData[0] + " " + validRowData[1];
            validRowData.splice(1, 1);
          }
        }
        // creating the row template, iterating through the valid data to create TDs
        var rowTemplate = "<tr>";
        for (var j = 0; j < validRowData.length; j++) {
          rowTemplate += "  <td> " + validRowData[j] + " </td> ";
        }
        rowTemplate += "   </tr>";
        // appending it to the table
        $('#textFileContentTable').append(rowTemplate);
      }
    });
  }

  // onclick of the button, load the table
  $('#fileReadButton').click(function(){
    populateTable('./text.txt');
  });
});

【讨论】:

  • 如何将每个数字放入不同的列。每列都有这些标题。 位置 状态 高 低 晴天 阴天 有雨的日子 有雪的日子
  • 现在更新我的解决方案,您只需要更改 元素
  • 解决方案已更新,如果解决了您的问题,请投票:)
  • 这太复杂了,在客户端做这件事毫无意义。
  • 我不同意,这是一个很小的文件,没有提到更大的文件(您的问题范围非常有限),如果您想要服务器端,请将逻辑复制到 php 表单中。
【解决方案2】:

运行以下 PHP 脚本:

<?php
function fixCities($better_row){
  $res = trim(preg_replace('/\s+/', ' ',$better_row));
  $pieces = explode(" ",$res);
  $num = count($pieces);

  switch( $num )
  {
  case 9:
     $temp = array($pieces[0]."&nbsp;". $pieces[1]);
     array_splice($pieces, 0, 2,$temp);
     break;
  case 10: 
     $temp = array($pieces[0]."&nbsp;" .$pieces[1] . "&nbsp;" .$pieces[2]);
     array_splice($pieces,0,3,$temp);
     break;
   default:
     // 8 col table;     
  }
  return $pieces;
}

$arr = file("whspdel.txt");
foreach($arr as $e){
  $lines[] = preg_replace('!\s!', ',', $e);
}

echo <<<THEAD
<table cellpadding=0 cellspacing=0>
<thead><th>Location</th><th>State</th><th>High</th><th>Low</th><th>Days Clear</th>
<th>Days Cloudy</th><th>Days with Preceipitation</th><th>Days with Snow</th>
THEAD;

$data = array_map("str_getcsv", $lines);
foreach($data as $row) {
  $i=0;
  echo "<tr>\n";
  $better_row = join(" ",$row);
  $split = fixCities($better_row);
  foreach ($split as $e) {
     if ($e == "") continue;
     if ($i==0){
        echo "<td class='left'>",$e,"</td>";
        $i++;
     }
     else
     {
        echo "<td class='phpcolor'>",$e,"</td>";
     }
  }
  echo "</tr>\n";
}
echo "</table>\n";
?>

将 OP 的文本文件转换为 HTML 表格,如下图所示:

<html>
<head>
<style>
table {
width:80%;
border:1px solid #fff;
box-shadow: -18px -8px 20px #ccc;
margin-left:13%;
}
tr {
width: 100%;
}
td {
  background:transparent;
  width:10%;
  border-top:1px solid #003;
  border-right:none;
  border-left:none;
  font: 62% Arial,Helvetica;
  padding:6px;
  text-align:right;
}
th {
font: 62% Arial,Helvetica;
}
.left {
text-align:left;
background:#ffdede;
}
.phpcolor {
background:#ccccff;
}
</style>
</head>
<body>
<table cellpadding=0 cellspacing=0>
<thead><th>Location</th>
    <th>State</th><th>High</th><th>Low</th><th>Days Clear</th>
    <th>Days Cloudy</th><th>Days with Preceipitation</th><th>Days with Snow</th>
<tr>
<td class='left'>Lander</td><td class='phpcolor'>WY</td><td class='phpcolor'>5557</td><td class='phpcolor'>99</td><td class='phpcolor'>-35</td><td class='phpcolor'>109</td><td class='phpcolor'>140</td><td class='phpcolor'>67</td></tr>
<tr>
<td class='left'>Milwaukee</td><td class='phpcolor'>WI</td><td class='phpcolor'>672</td><td class='phpcolor'>98</td><td class='phpcolor'>-7</td><td class='phpcolor'>79</td><td class='phpcolor'>177</td><td class='phpcolor'>124</td></tr>
<tr>
<td class='left'>Seattle</td><td class='phpcolor'>WA</td><td class='phpcolor'>400</td><td class='phpcolor'>94</td><td class='phpcolor'>12</td><td class='phpcolor'>55</td><td class='phpcolor'>233</td><td class='phpcolor'>163</td></tr>
<tr>
<td class='left'>Spokane</td><td class='phpcolor'>WA</td><td class='phpcolor'>2356</td><td class='phpcolor'>98</td><td class='phpcolor'>-16</td><td class='phpcolor'>95</td><td class='phpcolor'>187</td><td class='phpcolor'>112</td></tr>
<tr>
<td class='left'>Burlington</td><td class='phpcolor'>VT</td><td class='phpcolor'>332</td><td class='phpcolor'>91</td><td class='phpcolor'>6</td><td class='phpcolor'>54</td><td class='phpcolor'>217</td><td class='phpcolor'>168</td></tr>
<tr>
<td class='left'>Norfolk</td><td class='phpcolor'>VA</td><td class='phpcolor'>24</td><td class='phpcolor'>98</td><td class='phpcolor'>19</td><td class='phpcolor'>85</td><td class='phpcolor'>145</td><td class='phpcolor'>117</td></tr>
<tr>
<td class='left'>Richmond</td><td class='phpcolor'>VA</td><td class='phpcolor'>164</td><td class='phpcolor'>101</td><td class='phpcolor'>16</td><td class='phpcolor'>105</td><td class='phpcolor'>165</td><td class='phpcolor'>115</td></tr>
<tr>
<td class='left'>Salt&nbsp;Lake&nbsp;City</td><td class='phpcolor'>UT</td><td class='phpcolor'>4221</td><td class='phpcolor'>103</td><td class='phpcolor'>-11</td><td class='phpcolor'>129</td><td class='phpcolor'>152</td><td class='phpcolor'>86</td></tr>
<tr>
<td class='left'>Dallas</td><td class='phpcolor'>TX</td><td class='phpcolor'>551</td><td class='phpcolor'>106</td><td class='phpcolor'>10</td><td class='phpcolor'>130</td><td class='phpcolor'>152</td><td class='phpcolor'>89</td></tr>
<tr>
<td class='left'>Houston</td><td class='phpcolor'>TX</td><td class='phpcolor'>96</td><td class='phpcolor'>104</td><td class='phpcolor'>19</td><td class='phpcolor'>73</td><td class='phpcolor'>166</td><td class='phpcolor'>94</td></tr>
<tr>
<td class='left'>San&nbsp;Antonio</td><td class='phpcolor'>TX</td><td class='phpcolor'>788</td><td class='phpcolor'>102</td><td class='phpcolor'>16</td><td class='phpcolor'>90</td><td class='phpcolor'>165</td><td class='phpcolor'>83</td></tr>
<tr>
<td class='left'>Memphis</td><td class='phpcolor'>TN</td><td class='phpcolor'>258</td><td class='phpcolor'>101</td><td class='phpcolor'>12</td><td class='phpcolor'>121</td><td class='phpcolor'>151</td><td class='phpcolor'>112</td></tr>
<tr>
<td class='left'>Huron</td><td class='phpcolor'>SD</td><td class='phpcolor'>1281</td><td class='phpcolor'>100</td><td class='phpcolor'>-30</td><td class='phpcolor'>121</td><td class='phpcolor'>147</td><td class='phpcolor'>80</td></tr>
<tr>
<td class='left'>Rapid&nbsp;City</td><td class='phpcolor'>SD</td><td class='phpcolor'>3162</td><td class='phpcolor'>106</td><td class='phpcolor'>-30</td><td class='phpcolor'>106</td><td class='phpcolor'>127</td><td class='phpcolor'>95</td></tr>
</table>
	
</body>
</html>

数据的挑战之一是它不是 CSV 格式。一些项目后跟多个空格字符,而其他项目则有一个或两个。所以,我的第一个想法是减少这些字符,然后将文档转换为 CSV 格式。

使用 array_map() 提供了极大的便利:避免了构建 for 循环,并且可以快速地将 str_getcsv() 应用于文本文件的每一行。

preg_replace() 非常有助于替换过多的空白字符,HTML 实体 &amp;nbsp; 可以方便地用于包含多个单词的城市名称。

我还使用heredoc 来获得优势

更新: fixCities() 现在为不对齐的城市提供了更有用的修复,因为它们的名称由两个或三个单词组成。从@Chizzele 那里得到了关于拼接以使城市名称正确对齐的提示。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签