Skip to content

Instantly share code, notes, and snippets.

@tylor
Created September 29, 2011 22:10
Show Gist options
  • Save tylor/1252081 to your computer and use it in GitHub Desktop.
Save tylor/1252081 to your computer and use it in GitHub Desktop.
Simple PHP class to get shapefile rows using ogr
<?php
/**
* Could also look at parsing shapefiles manually: http://en.wikipedia.org/wiki/Shapefile#Shapefile_shape_format_.28.shp.29
*/
class wktFromZip {
function __construct($fid) {
// Extract zip file to tmp.
$file = file_load($fid);
$extracted_path = drupal_realpath('public://tmp/' . basename($file->filename, '.zip'));
$zip = new ArchiverZip(drupal_realpath($file->uri));
$zip_contents = $zip->listContents();
$zip->extract($extracted_path);
// Look for shapefiles.
$shapefiles = file_scan_directory($extracted_path, '/^.*\.(shp)$/');
foreach ($shapefiles as $shapefile) {
$ogr2ogr = '/Library/Frameworks/GDAL.framework/Versions/1.8/Programs/ogr2ogr'; // vget().
$command = $ogr2ogr . ' -f CSV /vsistdout/ ' . $shapefile->uri . ' -lco GEOMETRY=AS_WKT';
// Can also seek to arbitrary features quite easily, for example: ogr2ogr -f CSV /vsistdout/ vector.shp -lco GEOMETRY=AS_WKT -where 'fid in (1,2,3,4,5)'
// Grab CSV representation of the SHP and do something with it. Maybe better to do GeoJSON?
if (($handle = popen($command, "r")) !== FALSE) {
$header = array();
while (($data = fgetcsv($handle)) !== FALSE) {
// Hold onto the header so we can do field mapping.
if (empty($header)) {
$header = $data;
}
else {
$record = array_combine($header, $data);
//print $record['Label'];
// Do stuff, like push data into a node with a Geofield.
}
}
pclose($handle);
}
else {
throw new Exception('ogr2ogr could not execute');
}
}
file_unmanaged_delete_recursive($extracted_path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment