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
“read and select csv ” makes use of the built-in PHP functions
file( ) ,
count( ) ,
explode( ) ,
trim( ) ,
strtolower( ) and
end( ) .
01 <?php
02
03 // reads a csv file and returns a two-dimensional array of lines/fields
04 function read_csv ( $file , $delimiter )
05 {
06 $data_array = file ( $file ) ;
07 for ( $i = 0 ; $i < count ( $data_array ) ; $i ++ )
08 {
09 $parts_array [ $i ] = explode ( $delimiter , $data_array [ $i ] ) ;
10 }
11 return $parts_array ;
12 }
13
14 // reads a csv file and returns an two-dimensional array of lines/fields
15 function select_csv ( $file , $delimiter , $field , $query )
16 {
17 $data_array = file ( $file ) ;
18 for ( $i = 0 ; $i < count ( $data_array ) ; $i ++ )
19 {
20 $parts_array [ $i ] = explode ( $delimiter , $data_array [ $i ] ) ;
21 if ( trim ( strtolower ( $parts_array [ $i ] [ $field ] ) ) == trim ( strtolower ( $query ) ) )
22 {
23 $result_array [ ] = $parts_array [ $i ] ;
24 }
25 }
26 return $result_array ;
27 }
28
29
30 // ------------------- demonstration below --------------------
31
32
33 // this willl display all records in the csv file
34 $data = read_csv ( 'read_csv.txt' , '|' ) ;
35 for ( $i = 0 ; $i < count ( $data ) ; $i ++ )
36 {
37 for ( $u = 0 ; $u < count ( $data [ $i ] ) ; $u ++ )
38 {
39 echo $data [ $i ] [ $u ] . ' ' ;
40 if ( $data [ $i ] [ $u ] == end ( $data [ $i ] ) )
41 {
42 echo '<br>' ;
43 }
44 }
45 }
46
47
48 echo '<p>' ;
49
50
51 // this willl display all records where the value
52 // of the selected field matches the query
53 $data = select_csv ( 'read_csv.txt' , '|' , '1' , '1069167712' ) ;
54 for ( $i = 0 ; $i < count ( $data ) ; $i ++ )
55 {
56 for ( $u = 0 ; $u < count ( $data [ $i ] ) ; $u ++ )
57 {
58 echo $data [ $i ] [ $u ] . ' ' ;
59 }
60 echo '<br>' ;
61 }
62
63
64 ?>