Search code examples
phpmysqlgeojson

How to output geoJSON file from mysql spatial table?


I have a mysql spatial database ('mydb1') of one table ('pk'), that i obtained from a point shapefile using ogr2ogr tool. one row of this 'pk' table, is like:

 OGR_FID   SHAPE       CODIF    Position_X   Position_Y    Nom   Status
 1     [GEOMETRY-25o]  PAC182854  398235.38    414569.24    G-31   Vert

I need to output the geoJSON file of this table. I downloaded geoPHP library and used MySQL to GeoJSON script which i adapted to my settings, like below:

<?php
/**
* Title:   MySQL to GeoJSON (Requires https://github.com/phayes/geoPHP)
* Notes:   Query a MySQL table or view and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc.
* Author:  Bryan R. McBride, GISP
* Contact: bryanmcbride.com
* GitHub:  https://github.com/bmcbride/PHP-Database-GeoJSON
*/

# Include required geoPHP library and define wkb_to_json function
include_once('geoPHP/geoPHP.inc');
function wkb_to_json($wkb) {
    $geom = geoPHP::load($wkb,'wkb');
    return $geom->out('json');
}

# Connect to MySQL database
$conn = new PDO('mysql:host=localhost;dbname=mydb1','root','admin');

# Build SQL SELECT statement and return the geometry as a WKB element
$sql = 'SELECT *, AsWKB(SHAPE) AS wkb FROM pk';

# Try query or error
$rs = $conn->query($sql);
if (!$rs) {
    echo 'An SQL error occured.\n';
    exit;
}

# Build GeoJSON feature collection array
$geojson = array(
   'type'      => 'FeatureCollection',
   'features'  => array()
);

# Loop through rows to build feature arrays
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
    $properties = $row;
    # Remove wkb and geometry fields from properties
    unset($properties['wkb']);
    unset($properties['SHAPE']);
    $feature = array(
         'type' => 'Feature',
         'geometry' => json_decode(wkb_to_json($row['wkb'])),
         'properties' => $properties
    );
    # Add feature arrays to feature collection array
    array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>

But when i execute the code on the browser, i get totally a blank page. What's wrong should i fix to output my geoJSON file plz?


Solution

  • You should check the php logs for more information in case an error ocured. Make sure error reporting and display are enabled:

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    

    if no error show up inspect the $geojson object easiest would be using

    print_r($geojson);