PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > PHP教程 > 正文

    PHP处理文件

    作者:admin来源:网络浏览:时间:2020-11-24 12:53:46我要评论
    导读:一、PHP读写文件1、简单的读文件(file_get_contents方法)<?php$hack_home=file_get_contents("hack-home.html");if(date(&#39;H&#39;>12)...
    一、PHP读写文件
    1、简单的读文件(file_get_contents方法)

    1. <?php 
    2.  
    3. $hack_home = file_get_contents("hack-home.html"); 
    4. if(date('H' > 12)){ 
    5.     $hack_home = str_replace("{color}","blue",$hack_home); 
    6. }else
    7.     $hack_home = str_replace("{color}","yellow",$hack_home); 
    8. print $hack_home; 


    2、简单的写文件(file_put_contents方法)
     

    1. <?php 
    2.  
    3. $hack_home = file_get_contents("hack-home.html"); 
    4. if(date('H' > 12)){ 
    5.     $hack_home = str_replace("{color}","blue",$hack_home); 
    6. }else
    7.     $hack_home = str_replace("{color}","yellow",$hack_home); 
    8.  
    9. file_put_contents("ailx10-home.html",$hack_home); 

    二、精细的读写文件内容
    1、文件内容比较少(file方法)

    1. <?php 
    2.  
    3. foreach (file("ailx10-hackbiji.txt") as $line){ 
    4.     $line = trim($line); 
    5.     $info = explode("|",$line); 
    6.     print "<li><font color='red' >$info[0]</font>($info[1])</li>"
    7. fclose($f); 

    2、文件内容超级多
    fopen 打开文件

    fgets 读取文件一行
    feop 判断是否读到文件末尾
    fclose 关闭文件

    1. <?php 
    2.  
    3. $f = fopen("ailx10-hackbiji.txt","rb"); 
    4. while( (! feof($f)) && ($line = fgets($f)) ){ 
    5.     $line = trim($line); 
    6.     $info = explode("|",$line); 
    7.     print "<li><font color='blue' >$info[0]</font>($info[1])</li>"
    8. fclose($f); 

    三、处理CSV文件
    CSV文件是程序员非常喜欢的文件格式,它比Excel更加轻量级,它使用逗号进行数据分割


    和普通读写的差别是 fgetcsv 方法
    直接读出数组,非常适合结构化的数据
    同理,fputcsv方法直接把数组,写成csv文件
     

    1. <?php 
    2.  
    3. $f = fopen("ailx10.csv","rb"); 
    4. $i = 0; 
    5. while( (! feof($f)) && ($line = fgetcsv($f)) ){ 
    6.     $i +=1; 
    7.     if($i==1) 
    8.     { 
    9.         continue
    10.     }else { 
    11.  
    12.         $info = $line; 
    13.         print "<li><font color='blue' >@$info[0]</font>($info[1]),那时候是$info[3]年,我上$info[2]</li>"
    14.     } 
    15. fclose($f); 
    16. 也可以直接下载csv文件 
    17. fputcsv($fh,$row); 其中打开的文件是 php://output 
    1. <?php 
    2. try { 
    3.     $db = new PDO("mysql:host=127.0.0.1;dbname=hack""root"""); 
    4.     print "数据库连接成功~<br>"
    5.  
    6.     header("Content-Type: text/csv"); 
    7.     header("Content-Disposition:attachment; filename=ailx10.csv"); 
    8.     $fh = fopen("php://output","wb"); 
    9.     $que = $db->query('select * from study where subject like "web安全%"'); 
    10.     while($row = $que->fetch()){ 
    11.         fputcsv($fh,$row); 
    12.     } 
    13.     fclose($fh); 
    14. }catch (PDOException $e) { 
    15.     print "数据库连接失败,因为:" . $e->getMessage(); 
    16.  
    17. ?> 

     

    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-10-6450-1.html
    相关热词搜索: