Skip to content

Instantly share code, notes, and snippets.

@ckhung
Last active March 11, 2025 08:00
Show Gist options
  • Save ckhung/be5734eb258044bd86566ee1a9ef6dcf to your computer and use it in GitHub Desktop.
Save ckhung/be5734eb258044bd86566ee1a9ef6dcf to your computer and use it in GitHub Desktop.
convert a google sheet containing longitude and latitude fields into a csv file recognized by umap of osm
<?php
if (! (isset($_GET['html']) && filter_var($_GET['html'], FILTER_VALIDATE_URL))) {
echo 'needs "html" variable on command line';
return;
}
$url = $_GET['html'];
$htmlContent = file_get_contents($url);
$tmpHtmlFile = tempnam(sys_get_temp_dir(), 'html_');
$tmpCsvFile = tempnam(sys_get_temp_dir(), 'csv_');
file_put_contents($tmpHtmlFile, $htmlContent);
exec("html2csv.py < " . escapeshellarg($tmpHtmlFile) . " > " . escapeshellarg($tmpCsvFile));
$csvContent = file($tmpCsvFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
unlink($tmpHtmlFile);
foreach ($csvContent as $index => $row) {
$cols = str_getcsv($row);
array_shift($cols);
$iLong = -1;
$iLat = -1;
foreach ($cols as $i => $c) {
$ans = strpos(strtolower($c), "lon");
if ($iLong < 0 && $ans !== false && $ans == 0)
$iLong = $i;
$ans = strpos(strtolower($c), "lat");
if ($iLat < 0 && $ans !== false && $ans == 0)
$iLat = $i;
}
if ($iLong >= 0 && $iLat >= 0) {
$headerRow = $cols;
break;
}
}
if ($iLong<0 || $iLat<0) {
echo 'cannot find "lon" and "lat" header at the same time in any row';
return;
}
$filteredCsv = array(implode(',', $headerRow));
foreach (array_slice($csvContent, $index + 1) as $row) {
$cols = str_getcsv($row);
array_shift($cols);
if (is_numeric($cols[$iLat]) && is_numeric($cols[$iLong]))
$filteredCsv[] = implode(',', $cols);
}
unlink($tmpCsvFile);
header('Content-Type: text/plain');
echo implode("\n", $filteredCsv);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment