程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> php實現讀取和寫入tab分割的文件

php實現讀取和寫入tab分割的文件

編輯:PHP綜合

本文實例講述了php實現讀取和寫入tab分割的文件。分享給大家供大家參考。具體分析如下:

這段php代碼實現讀取和寫入tab分割的文件,包含兩個獨立的函數,一個讀,一個寫,例如cvs文件等

//
// save an array as tab seperated text file
//
function write_tabbed_file($filepath, $array, $save_keys=false){
  $content = '';
  reset($array);
  while(list($key, $val) = each($array)){
    // replace tabs in keys and values to [space]
    $key = str_replace("\t", " ", $key);
    $val = str_replace("\t", " ", $val);
    if ($save_keys){ $content .= $key."\t"; }
    // create line:
    $content .= (is_array($val)) ? implode("\t", $val) : $val;
    $content .= "\n";
  }
  if (file_exists($filepath) && !is_writeable($filepath)){ 
    return false;
  }
  if ($fp = fopen($filepath, 'w+')){
    fwrite($fp, $content);
    fclose($fp);
  }
  else { return false; }
  return true;
}
//
// load a tab seperated text file as array
//
function load_tabbed_file($filepath, $load_keys=false){
  $array = array();
  if (!file_exists($filepath)){ return $array; }
  $content = file($filepath);
  for ($x=0; $x < count($content); $x++){
    if (trim($content[$x]) != ''){
      $line = explode("\t", trim($content[$x]));
      if ($load_keys){
        $key = array_shift($line);
        $array[$key] = $line;
      }
      else { $array[] = $line; }
    }
  }
  return $array;
}
/*
** Example usage:
*/
$array = array(
  'line1' => array('data-1-1', 'data-1-2', 'data-1-3'),
  'line2' => array('data-2-1', 'data-2-2', 'data-2-3'),
  'line3' => array('data-3-1', 'data-3-2', 'data-3-3'),
  'line4' => 'foobar',
  'line5' => 'hello world'
);
// save the array to the data.txt file:
write_tabbed_file('data.txt', $array, true);
/* the data.txt content looks like this:
line1 data-1-1 data-1-2 data-1-3
line2 data-2-1 data-2-2 data-2-3
line3 data-3-1 data-3-2 data-3-3
line4 foobar
line5 hello world
*/
// load the saved array:
$reloaded_array = load_tabbed_file('data.txt',true);
print_r($reloaded_array);
// returns the array from above

希望本文所述對大家的php程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved