Skip to content

Instantly share code, notes, and snippets.

@netconstructor
Forked from mexitek/json_to_postgre.php
Created May 1, 2012 08:53
Show Gist options
  • Save netconstructor/2566529 to your computer and use it in GitHub Desktop.
Save netconstructor/2566529 to your computer and use it in GitHub Desktop.
Script to automate an import process from .json file to postgre DB.
<?php
# Configure
$DB_USER = 'admin';
$DB_PASS = 'qwerty';
$DB_HOST = 'localhost';
$DB_NAME = 'postgis-2-0';
// Param 3 when ran in shell will override this value
$DB_TABLE = 'public.florida_establishments_garman';
// Param 2 when ran in shell will override this value
$CATEGORY = 'misc';
// ===============================
// = Do NOT Edit Below This Line =
// ===============================
# Params
$CURRENT_SCRIPT = $argv[0];
$JSON_FILE = $argv[1];
$CATEGORY = isset($argv[2]) ? $argv[2]:$CATEGORY;
$POSTGRE_TABLE = isset($argv[3]) ? $argv[3]:$DB_TABLE;
# Open our file
$f = file_get_contents($JSON_FILE);
# Make sure file is good
if( $f === FALSE )
{
die('Could not open file.');
}
# Open Postgre Connections
else
{
$dbconn = pg_connect("host=$DB_HOST dbname=$DB_NAME user=$DB_USER password=$DB_PASS")
or die('Could not connect: ' . pg_last_error());
}
# Decode JSON into array
$points = json_decode( $f, true );
# Iterate our points
foreach($points as $p)
{
/*
$p['Latitude']
$p['Longitude']
$p['Establishment']
$p['Address_Phone']
*/
# Sanatize
$est = str_replace("'","\'",$p['Establishment']);
$add = str_replace("'","\'",$p['Address_Phone']);
# Insert into DB
pg_query($dbconn,"INSERT INTO $POSTGRE_TABLE (establishment,address_phone,category,location) VALUES ( '".$est."', '".$add."', '".$CATEGORY."',ST_Makepoint(".$p['Latitude'].",".$p['Longitude'].") )") or die("Could not execute this insert statement: ".pg_last_error());
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment