file handling
|read and select csv
this functions read csv (comma seperated values) files and return the content as an array.
the first one returns the whole file, the second acts like a select statement
perfect for file-based databases
full source of read and select csv [ line 1 - 52 ] | download read and select csv
| 1 | <?php |
| 2 | // reads a csv file and returns a two-dimensional array of lines/fields |
| 3 | function read_csv($file,$delimiter) |
| 4 | { |
| 5 | $data_array = file($file); |
| 6 | for ( $i = 0; $i < count($data_array); $i++ ) |
| 7 | { |
| 8 | $parts_array[$i] = explode($delimiter,$data_array[$i]); |
| 9 | } |
| 10 | return $parts_array; |
| 11 | } |
| 12 | // reads a csv file and returns an two-dimensional array of lines/fields |
| 13 | function select_csv($file,$delimiter,$field,$query) |
| 14 | { |
| 15 | $data_array = file($file); |
| 16 | for ( $i = 0; $i < count($data_array); $i++ ) |
| 17 | { |
| 18 | $parts_array[$i] = explode($delimiter,$data_array[$i]); |
| 19 | if(trim(strtolower($parts_array[$i][$field])) == trim(strtolower($query))) |
| 20 | { |
| 21 | $result_array[] = $parts_array[$i]; |
| 22 | } |
| 23 | } |
| 24 | return $result_array; |
| 25 | } |
| 26 | // ------------------- demonstration below -------------------- |
| 27 | // this willl display all records in the csv file |
| 28 | $data = read_csv('read_csv.txt','|'); |
| 29 | for ( $i = 0; $i < count($data); $i++ ) |
| 30 | { |
| 31 | for ( $u = 0; $u < count($data[$i]); $u++ ) |
| 32 | { |
| 33 | echo $data[$i][$u].' '; |
| 34 | if($data[$i][$u] == end($data[$i])) |
| 35 | { |
| 36 | echo '<br>'; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | echo '<p>'; |
| 41 | // this willl display all records where the value |
| 42 | // of the selected field matches the query |
| 43 | $data = select_csv('read_csv.txt','|','1','1069167712'); |
| 44 | for ( $i = 0; $i < count($data); $i++ ) |
| 45 | { |
| 46 | for ( $u = 0; $u < count($data[$i]); $u++ ) |
| 47 | { |
| 48 | echo $data[$i][$u].' '; |
| 49 | } |
| 50 | echo '<br>'; |
| 51 | } |
| 52 | ?> |
45 hits by 15 users in the last 30 minutes.