[GIS] Problem with reading data from PostGIS as KML file using PHP

kmlPHPpostgispostgis-1.5postgis-2.0

I am using the following PHP code in order to read data from PostGIS and save it in KML format as a file. When I load the page a document with ".PHP" extension is returned (not .kml) which inside has the data in KML format. The page returns no error, but the console of the developer tools gives the following note:

Resource interpreted as Document but transferred with MIME type
application/vnd.google-earth.kml+xml: http://mydomain.com/….

Does anyone have any idea what the problem could be?

The PHP code:

<?php

$dbconn = pg_connect("dbname='nyc' user='postgres' password='****' host='localhost'");
if (!$dbconn) {
    echo "Not connected : " . pg_error();
    exit;
}

$sql = 'SELECT *, ST_AsKML(ST_Transform(geom,26918)) AS kmlgm FROM nyc_census_blocks LIMIT 5';

 # Try query or error
$query_result = pg_query($dbconn, $sql);
if (!$query_result) {
    echo "An SQL error occured.\n";
    exit;
}

$kml ="<kml><Document>";

for ($i = 0; $i < pg_numrows($query_result); $i++) {

    $townname = pg_result($query_result, $i, 0);
    $townkml =  pg_result($query_result, $i, 1);

    $kml .= "<Placemark><name>Town: ".$townname."</name><description>".$townname."</description>".$townkml."</Placemark>\n";
}

$kml .= "</Document></kml>";

header('Content-Type: application/vnd.google-earth.kml+xml');

echo $kml;

pg_close($dbconn);
?>

and the kml data returned inside a file with ".php" suffix!!:

<kml><Document><Placemark><name>Town: 1</name><description>1</description>360850009001000</Placemark>
<Placemark><name>Town: 2</name><description>2</description>360850020011000</Placemark>
<Placemark><name>Town: 3</name><description>3</description>360850040001000</Placemark>
<Placemark><name>Town: 4</name><description>4</description>360850074001000</Placemark>
<Placemark><name>Town: 5</name><description>5</description>360850096011000</Placemark>
</Document></kml>

Best Answer

If you want to make browser download the generated KML, an extra header is needed:

header("Content-Disposition: attachment; filename=MY_KML_FILENAME.kml");

Otherwise, just ignore the message, it's harmless. Chrome doesn't recognize the KML-specific Content-Type, and expects ordinary text/xml or application/xml, but since it's all XML, it should be parsed correctly. Do you have any trouble displaying the KML in map application or Google Earth?

Related Question