php文件怎么转换txt文件,php – 解析txt文件并将它们转换为静态html文件

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值