This article mainly introduces the PHP implementation of Read and write tab segmentation of the file, involving PHP file reading and writing and string manipulation of the relevant skills, the need for friends can refer to the following
This article describes the PHP implementation of Read and write tab segmentation files. Share to everyone for your reference. The specific analysis is as follows:
This PHP code implements reading and writing tab-separated files, containing two separate functions, one read, one write, such as CVS files, etc.
Save an array as tab seperated text File//function write_tabbed_file ($filepath, $array, $save _keys=false) {$content = ''; Reset ($array); while (list ($key, $val) = per ($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 C Ontent looks like this:line1 data-1-1 data-1-2 data-1-3line2 data-2-1 data-2-2 data-2-3line3 data-3-1 data-3-2 Data-3-3lin E4 foobarline5 Hello world*///load the saved array: $reloaded _array = load_tabbed_file (' Data.txt ', true);p Rint_r ($ Reloaded_array);//returns the array from above