0

我正在使用 file_get_contents() 导入文本文件。在文本文件中,格式如下(示例):

3434,83
​​,8732722 834,93,4983293
9438,43933,34983

依此类推...基本上它遵循以下模式:整数,逗号分割它,第二个整数,另一个逗号分割它,第三个整数,然后新行开始。我需要将其放入相应格式的表格中。所以换句话说,我将有一个 3 列的表,文本文件中的每一行都是表中的新行。

这必须用 <table> <tr> 和 <td> 转码成一个简单的 html 表

我从来没有使用过多维数组并用它来分割文本。这就是我寻求帮助的原因。对此,我真的非常感激!:)

4

3 回答 3

1

您可以执行以下操作:

$filename = 'abc.txt';
$content = file_get_contents($filename);
$explodedByBr = explode('<br/>', $content);
$table = "<table border='1'>";
foreach ($explodedByBr as $brExplode) {
  $explodedByComma = explode(',', $brExplode);

  $table .= "<tr>";
  foreach ($explodedByComma as $commaExploded) {
    $table .= "<td>" .$commaExploded. "</td>";
  }
  $table .= "<tr/>";
}
$table .= "</table>";

echo $table;

abc.txt 具有以下格式的数据:

3434,83
​​,8732722 834,93,4983293
9438,43933,34983

于 2012-08-06T07:56:12.110 回答
0

尝试这个:

将文件读入一个数组,然后通过传递它来处理数组的每一行,将其列化array_walk

<?php
function addElements( &$v, $k ) {
    $v1 = explode( ',', $v ); // break it into array
    $v2 = '';
    foreach( $v1 as $element ) {
        $v2 .= '<td>'.$element.'</td>';
            // convert each comma separated value into a column
    }
    $v = '<tr>'.$v2.'</tr>'; // add these columns to a row and return
}

// read the whole file into an array using php's file method.
$file = file( '1.txt' );
// now parse each line of the array so that we convert each line into 3 columns.
// For this, i use array_walk function which calls a function, addElements, 
// in this case to process each element in the array.
array_walk( $file, 'addElements' );
?>
<html>
     <head></head>
     <body>
         <table border="0">
             <?php echo implode('',$file);?>
         </table>
     </body>
</html>

希望能帮助到你。请参阅 php 文档以获取filearray_walk。这些都是简单方便的功能。

于 2012-08-06T07:30:58.620 回答
0
<?php
    $file = 'path/to/file.txt';
    echo '<table>';
    while(!feof($file)) {
        $line = fgets($file);

        echo '<tr><td>' . implode('</td><td>',explode(',',$line)) . '</td></tr>';
    }
    echo '</table>';
?>
于 2012-08-06T07:28:39.417 回答