您可以逐个从文件中获取行,而不是获取整个文件,然后单独格式化它们并将它们放入变量中,以便在页面上回显.然而,Dontfeedthecode提出的方法迄今为止更优越,更高效,我已经撤回原文,并希望他会赞同我对他的想法做了什么.
$files = glob("*.txt"); // Scan directory for .txt files
// Check that there are .txt files in directory
if ($files !== false) {
$numberOfFiles = count($files); // Count number of .txt files in directory
// Check if number of files is greater than one
if ($numberOfFiles > 1) {
// Advanced loop will go here to process multiple txt files
} else {
$text_array = array();
$file_handle = fopen ($files[0], "r"); // Open file
$text_array = stream_get_contents($file_handle);
$text_array = explode("\n", $text_array);
// get the top three lines
$page_title = trim($text_array[0]);
$all_lines = '
' . trim($text_array[0]) . ' - ' . trim($text_array[1]) . ' - ' . trim($text_array[2]) . '
';// delete the top four array elements
$text_array[0] = $text_array[1] = $text_array[2] = $text_array[3] = '';
// get the remaining text
$text_block = trim(implode($text_array));
fclose ($file_handle); // Close file connection
} // endifs for first if(... statements
}
?>
HTML输出:
<?php echo $page_title; ?><?php echo $all_lines . "\n" . '
' . $text_block .'
'. "\n"; ?>A variable ready to print to file:
$print_to_file = '
' . $page_title . '' . $text_block .'
'. "\n" .'
';
echo $print_to_file;
?>
HTML在变量中看起来有点位移,但在打印时出现正确.
最后,一个版本放一个< p>标记每行文本.
$files = glob("*.txt"); // Scan directory for .txt files
// Check that there are .txt files in directory
if ($files !== false) {
$numberOfFiles = count($files); // Count number of .txt files in directory
// Check if number of files is greater than one
if ($numberOfFiles > 1) {
// Advanced loop will go here to process multiple txt files
} else {
$text_array = array();
$file_handle = fopen ($files[0], "r"); // Open file
$text = stream_get_contents($file_handle);
// get the top three lines
$text_array = explode("\n", $text);
$page_title = trim($text_array[0]);
$all_lines = '
' . $text_array[0] . ' - ' . $text_array[1] . ' - ' . $text_array[2] . '
';// set up something to split the lines by and add the
tags
$text_array = str_replace("\n","
\nxxx", $text);
$text_array = explode("xxx", $text_array);
// delete the top four array elements
$text_array[0] = $text_array[1] = $text_array[2] = $text_array[3] = '';
// get the remaining text
$text_block = trim(implode($text_array));
}
}
?>
这个版本可以使用与上面相同的html / php块