|
//
// 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
|