Importing a CSV File
view original csv file
$filename = "contacts.csv";
$infile = fopen($filename, "r") or exit("Unable to open data file.");
echo "Display as a Table of Records and Fields:
";
$my_data = array();
$count = 0;
while ( ( $record = fgetcsv($infile) ) !== FALSE) {
$my_data[$count] = array();
$my_data[$count] = $record;
$count++;
}
fclose ($infile);
echo "";
print_r ($my_data);
echo "
";
echo "Filter for ZIP 60267 or State CA
";
foreach ( $my_data as $record )
{
if ( $record[4] == 'CA' || $record[5] === '60267' ) {
echo "";
print_r ( $record );
echo "
";
}
}
// preg_match - match a regex w/ string
echo 'if(preg_match("/[a-zA-Z0-9_]+/", "Hey this is a valid expression")) ';
if(preg_match("/[a-zA-Z0-9_ ]+/", "Hey this is a valid expression")){
echo "Match
";
}
echo 'if(preg_match("/\w/", "Hey this is a valid expression")) ';
if(preg_match("/\w/", "Hey this is a valid expression")){ // allChars#_
echo "Match
";
}
echo 'if(preg_match("/CA/i+", "I live in ca")) ';
if(preg_match("/CA/i", "I live in ca")){ // case insens
echo "Match
";
}
?>
Reading an Unstructured File into an Array
To make the infile invisible to everyone but you:
$ chmod 700 'filename'
original file is invisible but PHP can read it...
Dump Array Contents:
Array
(
[0] => 36
[1] => 76
[2] => 23
[3] => 34.4
[4] => 87
[5] => 98.6
[6] => 12
[7] => 100.5
[8] => 34
[9] => 87
[10] => 123
[11] => 9.7
)
Split Array into Elements:
1: 36
2: 76
3: 23
4: 34.4
5: 87
6: 98.6
7: 12
8: 100.5
9: 34
10: 87
11: 123
12: 9.7
Largest: 123
Smallest: 9.7
Average: 60.1
Unable to open data file.