php parse gpx

So you’ve been digging about on the internet looking for a working example of a php script that will parse a .gpx file and you keep banging your head against the same walls – little snippets here and there or hideously complicated class parsers when all you really want is a simple, straightforward working example.

(By the way – what’s happened to Google? The number of sites in the top results that are nothing more than scraped versions of the php manual is shocking!)

As for a simple bit of code that reads a gpx file and sends it to a database – look no further.

I’ll spare you all the usual boring stuff about gpx being an xml file which is yadda, yadda…

Firstly, here’s a sample bit of a gpx file. It’s the first few entries for Scotland’s Munros (mountains of 3,000 feet or higher).


If you would like your own full version of this gpx file you can get one for free from the excellent, site.

Now what you have been searching for – a working example of a php script that will read a .gpx file and write it to a database.

foreach($xml as $munro){

	$attrs = $munro->attributes(); //fetches the *attributes* of a tag, e.g.  - attributes are 'small' and 'low' - required for lat and long 
	$lat = $attrs['lat'];
	$lon = $attrs['lon'];
	//echo the components of the gpx file
	echo 'lat: ' . $lat . ' long: ' . $lon . ' height: ' . $munro->ele . ' name: ' . $munro->name . ' cmt: ' . $munro->cmt . ' desc: ' . $munro->desc . ' sym: ' . $munro->sym . '
'; $ele = $munro->ele; //elevation (height) tag //**name and comment field are wrong way round in gpx file** $cmt = $munro->name; $name = mysql_real_escape_string($munro->cmt); //the comment tag , escaped because this field data contains apostrophes ' $desc = mysql_real_escape_string($munro->desc); //the description tag , escaped because this field data also contains apostrophes ' $sym = $munro->sym; //the symbol tag $query = ("INSERT INTO `munros` (`id`, `Name`, `Lat`, `Long`, `Height`, `Comment`, `Description`, `Symbol`) VALUES ('$i', '$name', '$lat', '$lon', '$ele', '$cmt', '$desc', '$sym')"); $insert_sql = mysql_query($query); echo mysql_error() . "
"; } ?>

Notice that the wpt

tag in the gpx file has two attributes, latitude and longitude, and that an attributes function must be called within the php script to snag the contents of both.