当前位置:首页 > PHP教程 > php文件操作 > 列表

php实现读取和写入tab分割的文件

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-27 14:10:23 浏览: 评论:0 

这篇文章主要介绍了php实现读取和写入tab分割的文件,涉及php文件读写及字符串操作的相关技巧,需要的朋友可以参考下。

本文实例讲述了php实现读取和写入tab分割的文件,分享给大家供大家参考,具体分析如下:

这段php代码实现读取和写入tab分割的文件,包含两个独立的函数,一个读,一个写,例如cvs文件等。

  1. // 
  2. // save an array as tab seperated text file 
  3. // 
  4. function write_tabbed_file($filepath, $array, $save_keys=false){ 
  5.   $content = ''; 
  6.   reset($array); 
  7.   while(list($key, $val) = each($array)){ 
  8.     // replace tabs in keys and values to [space] 
  9.     $key = str_replace("\t", " ", $key); 
  10.     $val = str_replace("\t", " ", $val); 
  11.     if ($save_keys){ $content .= $key."\t"; } 
  12.     // create line: 
  13.     $content .= (is_array($val)) ? implode("\t", $val) : $val; 
  14.     $content .= "\n"; 
  15.   } 
  16.   if (file_exists($filepath) && !is_writeable($filepath)){  
  17.     return false; 
  18.   } 
  19.   if ($fp = fopen($filepath, 'w+')){ 
  20.     fwrite($fp, $content); 
  21.     fclose($fp); 
  22.   } 
  23.   else { return false; } 
  24.   return true; 
  25. } 
  26. // 
  27. // load a tab seperated text file as array 
  28. // 
  29. function load_tabbed_file($filepath, $load_keys=false){ 
  30.   $array = array(); 
  31.   if (!file_exists($filepath)){ return $array; } 
  32.   $content = file($filepath); 
  33.   for ($x=0; $x < count($content); $x++){ 
  34.     if (trim($content[$x]) != ''){ 
  35.       $line = explode("\t", trim($content[$x])); 
  36.       if ($load_keys){ 
  37.         $key = array_shift($line); 
  38.         $array[$key] = $line; 
  39.       } 
  40.       else { $array[] = $line; } 
  41.     } 
  42.   } 
  43.   return $array; 
  44. } 
  45. /* 
  46. ** Example usage: 
  47. */ 
  48. $array = array( 
  49.   'line1' => array('data-1-1', 'data-1-2', 'data-1-3'), 
  50.   'line2' => array('data-2-1', 'data-2-2', 'data-2-3'), 
  51.   'line3' => array('data-3-1', 'data-3-2', 'data-3-3'), 
  52.   'line4' => 'foobar', 
  53.   'line5' => 'hello world' 
  54. ); 
  55. // save the array to the data.txt file: 
  56. write_tabbed_file('data.txt', $array, true); 
  57. /* the data.txt content looks like this: 
  58. line1 data-1-1 data-1-2 data-1-3 
  59. line2 data-2-1 data-2-2 data-2-3 
  60. line3 data-3-1 data-3-2 data-3-3 
  61. line4 foobar 
  62. line5 hello world 
  63. */ 
  64. // load the saved array: 
  65. $reloaded_array = load_tabbed_file('data.txt',true); 
  66. print_r($reloaded_array); 
  67. // returns the array from above

Tags: php读取文件

分享到: