This article describes the PHP implementation of reading and writing tab segmentation files. Share to everyone for your reference. The specific analysis is as follows:
This PHP code implements read and Write tab split files, contains two separate functions, one reads, one writes, such as CVS files, etc.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66-67 |
"////Save an array as tab seperated text File//function Write_tabbed_file ($filepath, $array, $save _keys=false) {$content = '; reset ($array); while (the list ($key, $val) = each ($array)) {//Replace tabs in keys and values to [spaces] $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+ ')) {Fwri Te ($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 ($l Oad_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 (' DA Ta-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 |
I hope this article will help you with your PHP programming.