首頁  >  文章  >  後端開發  >  php實作讀寫tab分割的文件

php實作讀寫tab分割的文件

*文
*文原創
2017-12-28 15:54:241917瀏覽

本文主要介紹了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]) != &#39;&#39;){
      $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(
  &#39;line1&#39; => array(&#39;data-1-1&#39;, &#39;data-1-2&#39;, &#39;data-1-3&#39;),
  &#39;line2&#39; => array(&#39;data-2-1&#39;, &#39;data-2-2&#39;, &#39;data-2-3&#39;),
  &#39;line3&#39; => array(&#39;data-3-1&#39;, &#39;data-3-2&#39;, &#39;data-3-3&#39;),
  &#39;line4&#39; => &#39;foobar&#39;,
  &#39;line5&#39; => &#39;hello world&#39;
);
// save the array to the data.txt file:
write_tabbed_file(&#39;data.txt&#39;, $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(&#39;data.txt&#39;,true);
print_r($reloaded_array);
// returns the array from above

相關推薦:

php 檔案讀取系列方法詳解

php 檔案類型的判斷範例程式碼

php 檔案快取函數

#

以上是php實作讀寫tab分割的文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn