Created
March 18, 2011 21:56
-
-
Save niczak/876921 to your computer and use it in GitHub Desktop.
CSV Parser -> PostgreSQL Inserter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
csvparse.php | |
Function that will parse a CSV and insert | |
data into a postgres database. | |
Revised: 3/18/2011, Nicholas Kreidberg | |
CSV Structure [For This Example]: | |
1,1001,Description,Foo,Bar | |
2,1002,Description,Foo,Bar | |
3,1003,Description,Foo,Bar | |
4,1004,Description,Foo,Bar | |
... | |
All I care about in this example are the | |
numerical codes (100x) and the description | |
that follows. | |
*/ | |
if(!$sFile = file_get_contents("./sci.csv")) | |
die("Invalid or empty file passed to file_get_contents()."); | |
$aCSV = str_getcsv($sFile); | |
$aValues = array(); | |
foreach($aCSV as $sVar=>$sVal) | |
{ | |
// RegEx check for science code | |
if(preg_match("/\d{4}$/", $sVal)) | |
{ | |
if(empty($aValues[$sVal])) | |
$aValues[$sVal] = $aCSV[++$sVar]; | |
} | |
} | |
if(empty($aValues)) | |
die("Failed to convert CSV to associative array."); | |
$hDB = fnDB_Open("rw"); | |
$iCnt = 0; | |
foreach($aValues as $sCode=>$sDesc) | |
{ | |
$rRes = pg_query($hDB, "INSERT INTO list_science_codes (drev, sncode, sdesc) ". | |
"VALUES ('now', '$sCode', '$sDesc')"); | |
if(!$rRes) | |
die("Database query failed for code: $sCode."); | |
$iCnt++; | |
} | |
pg_close($hDB); | |
printf("\n%d records inserted into database.\n", $iCnt); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment