johnmahugu

php - read and write tab delimited files

Jun 14th, 2015
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.03 KB | None | 0 0
  1.  
  2.  
  3. //
  4. // save an array as tab seperated text file
  5. //
  6.  
  7. function write_tabbed_file($filepath, $array, $save_keys=false){
  8.     $content = '';
  9.  
  10.     reset($array);
  11.     while(list($key, $val) = each($array)){
  12.  
  13.         // replace tabs in keys and values to [space]
  14.         $key = str_replace("\t", " ", $key);
  15.         $val = str_replace("\t", " ", $val);
  16.  
  17.         if ($save_keys){ $content .=  $key."\t"; }
  18.  
  19.         // create line:
  20.         $content .= (is_array($val)) ? implode("\t", $val) : $val;
  21.         $content .= "\n";
  22.     }
  23.  
  24.     if (file_exists($filepath) && !is_writeable($filepath)){
  25.         return false;
  26.     }
  27.     if ($fp = fopen($filepath, 'w+')){
  28.         fwrite($fp, $content);
  29.         fclose($fp);
  30.     }
  31.     else { return false; }
  32.     return true;
  33. }
  34.  
  35. //
  36. // load a tab seperated text file as array
  37. //
  38. function load_tabbed_file($filepath, $load_keys=false){
  39.     $array = array();
  40.  
  41.     if (!file_exists($filepath)){ return $array; }
  42.     $content = file($filepath);
  43.  
  44.     for ($x=0; $x < count($content); $x++){
  45.         if (trim($content[$x]) != ''){
  46.             $line = explode("\t", trim($content[$x]));
  47.             if ($load_keys){
  48.                 $key = array_shift($line);
  49.                 $array[$key] = $line;
  50.             }
  51.             else { $array[] = $line; }
  52.         }
  53.     }
  54.     return $array;
  55. }
  56.  
  57. /*
  58. ** Example usage:
  59. */
  60.  
  61. $array = array(
  62.     'line1'  => array('data-1-1', 'data-1-2', 'data-1-3'),
  63.     'line2' => array('data-2-1', 'data-2-2', 'data-2-3'),
  64.     'line3'  => array('data-3-1', 'data-3-2', 'data-3-3'),
  65.     'line4' => 'foobar',
  66.     'line5' => 'hello world'
  67. );
  68.  
  69. // save the array to the data.txt file:
  70. write_tabbed_file('data.txt', $array, true);
  71.  
  72. /* the data.txt content looks like this:
  73. line1   data-1-1    data-1-2    data-1-3
  74. line2   data-2-1    data-2-2    data-2-3
  75. line3   data-3-1    data-3-2    data-3-3
  76. line4   foobar
  77. line5   hello world
  78. */
  79.  
  80. // load the saved array:
  81. $reloaded_array = load_tabbed_file('data.txt',true);
  82.  
  83. print_r($reloaded_array);
  84. // returns the array from above
Advertisement
Add Comment
Please, Sign In to add comment