php文件怎么转换txt文件,php – 解析txt文件并将它们转换为静态html文件
发布日期:2021-06-24 17:42:11 浏览次数:2 分类:技术文章

本文共 2366 字,大约阅读时间需要 7 分钟。

您可以逐个从文件中获取行,而不是获取整个文件,然后单独格式化它们并将它们放入变量中,以便在页面上回显.然而,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块

转载地址:https://blog.csdn.net/weixin_34190683/article/details/115502319 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:app 上传 php,APP端压缩上传,与PHP端解压实现
下一篇:php 字符转数字,PHP怎么将字符串转换成数字

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月22日 03时25分07秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章