php学习(5):文件包含
今天学习高级部分
先从简单的开始,时间和日期:
1 |
|
解释一下,
1 | h: hour |
显示如图所示。
在网站上可以自动更新版权年份:
1 | <html> |
如图所示。
最简单的年月日表示:
1 |
|
再来介绍一个新函数:
1 | strtotime();#用来我们自己设定一个时间,下面的date函数执行我们这个时间 |
1 |
|
下面正式开始PHP高级部分:
include和require
他们其实是差不多的,只不过如果require执行错误会结束整个脚本的执行。
如果include执行错误只会在它这里跳过,不影响下面语句的执行。
举例子,先写一个php文件
1 |
|
也就是一个版权文件
下面用include将其展示在html前端页面上。
1 | <html> |
再来一个例子:
1 | #先写一个PHP文件 |
再写前端
1 | <html> |
下面看require的例子:
1 | <html> |
执行结果应该是找不到文件以及之后的部分都不能显示了。如图:
只能到这里。
下面开始读取文件:
1 | readfile()#读取文件并将其写到缓冲区。 |
我们写一个txt文件
1 | AJAX = Asynchronous JavaScript and XML |
然后读取:
1 |
|
读取结果!
1 | fopen()比readfile()提供了更多的选择。 |
1 | fopen()第一个参数表示打开哪个文件,第二个参数表示哪种方式打开。下面是第二个参数的图。 |
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
1 | fread()是从打开的文件中读取数据。第一个参数是文件名,第二个参数是读取的二最大字节数!也就是限制了读取数量 |
因为一个文件被fopen打开后,服务器不希望它一直打开着占内存。所以我们最好在代码中关闭它。
1 |
|
下面看fgets()函数,用于从文件中读取一行。
1 |
|
调用fgets()后,文件指针指向文件下一行。
下面看检查文件结束符—feof()
对于遍历未知长度的数据非常有用。
1 |
|
既然有读取一行,也有读取一个字符!—fgetc()
1 |
|
调用fgetc后,文件指针向下一个字符移动。
下次学写文件!
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment