php读取文件内容操作以及实例分享

php读取文件内容:

-----第一种方法-----fread()--------

?

1

2

3

4

5

6

7

8

<?php

$file_path = "test.txt";

if(file_exists($file_path)){

$fp = fopen($file_path,"r");

$str = fread($fp,filesize($file_path));//指定读取大小,这里把整个文件内容读取出来

echo $str = str_replace("\r\n","<br />",$str);

}

?>

--------第二种方法------------

?

1

2

3

4

5

6

7

8

<?php

$file_path = "test.txt";

if(file_exists($file_path)){

$str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中

$str = str_replace("\r\n","<br />",$str);

echo $str;

}

?>

-----第三种方法------------

?

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$file_path = "test.txt";

if(file_exists($file_path)){

$fp = fopen($file_path,"r");

$str = "";

$buffer = 1024;//每次读取 1024 字节

while(!feof($fp)){ //循环读取,直至读取完整个文件

$str .= fread($fp,$buffer);

}

$str = str_replace("\r\n","<br />",$str);

echo $str;

}

?>

-------第四种方法--------------

?

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$file_path = "test.txt";

if(file_exists($file_path)){

$file_arr = file($file_path);

for($i=0;$i<count($file_arr);$i++){ //逐行读取文件内容

echo $file_arr[$i]."<br />";

}

/*

foreach($file_arr as $value){

echo $value."<br />";

}*/

}

?>

----第五种方法--------------------

?

1

2

3

4

5

6

7

8

9

10

11

12

<?php

$file_path = "test.txt";

if(file_exists($file_path)){

$fp = fopen($file_path,"r");

$str ="";

while(!feof($fp)){

$str .= fgets($fp);//逐行读取。如果fgets不写length参数,默认是读取1k。

}

$str = str_replace("\r\n","<br />",$str);

echo $str;

}

?>

如图将上述的文本内容打印到网页上,代码如下

<?php 
$file_path="个人数据.txt";//此处可以将自己设置的文本的路径添加进来
$file_arr = file($file_path);
$file_mes[] = array();
for($i=0;$i<count($file_arr);$i++){//逐行读取文件内容
    $file_mes[$i] = $file_arr[$i] ;//将读取到的内容放入到所定义的数组中
    $data[]=explode('|', $file_mes[$i]);//按照|来分割字符
    
}
//var_dump($data);用来调试输出的
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <table border="1px solid red" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>邮箱</th>
                <th>网址</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $line): ?><!-- 遍历行 -->
                <tr>
                    <?php foreach ($line as $col): ?><!-- 遍历行中的数组 -->
                        <td><?php echo trim($col); ?> </td><!-- trim函数是删除字符串两边的空格的 -->
                    <?php  endforeach ?>
                </tr>
            <?php endforeach ?>
        </tbody>
    </table>
    
</body>
</html>

网页上的打印效果如下

猜你喜欢

转载自blog.csdn.net/weixin_43797908/article/details/103802628