php生成txt

访问PHP的时候生成TXT并自动下载。

 

第一步:处理中文文件名:

    
filename=" . iconv ( "UTF-8", "gbk//IGNORE", "缴费数据导出" ) . ".txt"

  1. $ua = $_SERVER["HTTP_USER_AGENT"];    
  2. $filename = "中文文件名.txt";    
  3. $encoded_filename = urlencode($filename);    
  4. $encoded_filename = str_replace("+""%20"$encoded_filename);    

 

 

 

以上方法可支持下载中文文件名。

 

第二步:生成TXT文件

  1. header("Content-Type: application/octet-stream");     
  2. //
    header ( "Content-type:text/plain" );

  3. if (preg_match("/MSIE/"$_SERVER['HTTP_USER_AGENT']) ) {      
  4.     header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');      
  5. elseif (preg_match("/Firefox/"$_SERVER['HTTP_USER_AGENT'])) {      
  6.     header('Content-Disposition: attachment; filename*="utf8' .  $filename . '"');      
  7. else {      
  8.     header('Content-Disposition: attachment; filename="' .  $filename . '"');      
  9. }  

兼容各种浏览器。

 

第三步:输出内容

                         echo $txt_data; 
 
             $fp = fopen('php://output', 'a');
              fwrite($fp,$txt_data);
               fclose($fp);

直接用echo输出,“\r\n”用以换行。

输出的内容即为txt里的内容

 

这个功能也可以生成doc文件,只要把后缀改成.doc即可,只是一个简单的doc文件

,里面没有图片和链接这些

猜你喜欢

转载自blog.csdn.net/youcijibi/article/details/80828792