php gpx manipulation

While prepping for the Rando ride this month I took the time to make a script which numbers waypoints and splits track segments into chunks that the Garmin Etrex Vista can handle without truncating them. It’s rudimentary, but if it helps someone get over the hurdle of converting exported Bikely .gpx files with cues into something usable on the unit then mission accomplished. If you want to run it you’ll have to have access to a web server where you can stuff the files or have an instance of a server running on your local machine. Here’s what it does to a .gpx file…

  1. Open file
  2. While the file’s open, run a loop to find all the <name> tags and append with numeric tag (001, 002, etc…).
  3. At the same time, look for <trkpt> tags. Count off 300 and then stuff in some more tags to segment the track.

Running the php file in your browser (I used Firefox) will output everything to your screen sans markup…

  1. ‘View source’ to see the full output and ‘save as’ the file with the ‘.gpx’ extension.
  2. Import into Garmin Roadtrip, create a folder to save to the Etrex with the result.
  3. Create a route and drag all the waypoints over. The numbering will force them to fall in order and automatically create turn-by-turn directions. (this works great if you want your unit to ‘beeep’ every time you’re supposed to turn on a cue…)
  4. Plug in the Etrex, turn it on, and save the folder to your unit.
  5. Enjoy!

Actual code after the break…

// put the file in the same directory & fill in between the quotes with the name...
$file = "In-Search-of-Liberty-102-miles.gpx"; 
$fp = fopen($file, "r") or die("Could not open file"); 

$i=0; // variable for counting up '<name>' tags
$j=0; // variable for counting up '</trkpt>' tags

if ($fp) {
 while (($buffer = fgets($fp, 4096)) !== false) {
 if(preg_match('(<name>)', $buffer)){
 // section below creates appropriate length '0' leader for waypoint tags
 if($i < 10) {
 $lead = '00';
 }else if ($i < 100) {
 $lead = '0';
 $lead = '';
 $flah = str_replace("<name>",$new,$buffer);
 echo $flah;
 }elseif (preg_match('(</trkpt>)', $buffer)){
 if ($j == 300){
 $trackFlah = str_replace("</trkpt>",$new,$buffer);
 echo $trackFlah;
 echo $buffer;
 echo $buffer;
 if (!feof($fp)) {
 echo "Error: unexpected fgets() fail\n";

Creative Commons License
Enjoy, but use at your own peril: php-gpx-manipulator by david hopkins is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License.

3 thoughts on “php gpx manipulation

  1. Pingback: you earrrrned it « bikesncoffee

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s