- <?php
- $hack_home = file_get_contents("hack-home.html");
- if(date('H' > 12)){
- $hack_home = str_replace("{color}","blue",$hack_home);
- }else{
- $hack_home = str_replace("{color}","yellow",$hack_home);
- }
- print $hack_home;
2、简单的写文件(file_put_contents方法)
- <?php
- $hack_home = file_get_contents("hack-home.html");
- if(date('H' > 12)){
- $hack_home = str_replace("{color}","blue",$hack_home);
- }else{
- $hack_home = str_replace("{color}","yellow",$hack_home);
- }
- file_put_contents("ailx10-home.html",$hack_home);
二、精细的读写文件内容
1、文件内容比较少(file方法)
- <?php
- foreach (file("ailx10-hackbiji.txt") as $line){
- $line = trim($line);
- $info = explode("|",$line);
- print "<li><font color='red' >$info[0]</font>($info[1])</li>";
- }
- fclose($f);
2、文件内容超级多
fopen 打开文件
- <?php
- $f = fopen("ailx10-hackbiji.txt","rb");
- while( (! feof($f)) && ($line = fgets($f)) ){
- $line = trim($line);
- $info = explode("|",$line);
- print "<li><font color='blue' >$info[0]</font>($info[1])</li>";
- }
- fclose($f);
三、处理CSV文件
CSV文件是程序员非常喜欢的文件格式,它比Excel更加轻量级,它使用逗号进行数据分割
和普通读写的差别是 fgetcsv 方法
直接读出数组,非常适合结构化的数据
同理,fputcsv方法直接把数组,写成csv文件
- <?php
- $f = fopen("ailx10.csv","rb");
- $i = 0;
- while( (! feof($f)) && ($line = fgetcsv($f)) ){
- $i +=1;
- if($i==1)
- {
- continue;
- }else {
- $info = $line;
- print "<li><font color='blue' >@$info[0]</font>($info[1]),那时候是$info[3]年,我上$info[2]</li>";
- }
- }
- fclose($f);
- 也可以直接下载csv文件
- fputcsv($fh,$row); 其中打开的文件是 php://output
- <?php
- try {
- $db = new PDO("mysql:host=127.0.0.1;dbname=hack", "root", "");
- print "数据库连接成功~<br>";
- header("Content-Type: text/csv");
- header("Content-Disposition:attachment; filename=ailx10.csv");
- $fh = fopen("php://output","wb");
- $que = $db->query('select * from study where subject like "web安全%"');
- while($row = $que->fetch()){
- fputcsv($fh,$row);
- }
- fclose($fh);
- }catch (PDOException $e) {
- print "数据库连接失败,因为:" . $e->getMessage();
- }
- ?>