Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zatarra
Last active December 21, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zatarra/6351139 to your computer and use it in GitHub Desktop.
Save zatarra/6351139 to your computer and use it in GitHub Desktop.
#!/usr/bin/env php -q
<?php
/*
* StravaMerger © David Gouveia - http://www.davidgouveia.net
* Simple script to merge tracking data from Strava's exported GPX files.
* The backtrack_limit is there because some files could not be parsed due to their size.
* Feel free to raise the limit but be carrefull not to cross the limit.
* Instead of using regex, I could have used a XML cursor to overcome the backtrack limit
* but either I would have to use the php_xml extension or build my own parser.
*/
ini_set("pcre.backtrack_limit", "10000000");
if ( !trim( $argv[1] ) || trim( !$argv[2] ) || sizeof($argv) < 4 )
die("Usage:\n$argv[0] file1.gpx file2.gpx <fileN.gpx> output.gpx\n" );
$segments ="";
for($i = 1; $i < sizeof($argv) - 1; $i++)
{
echo "Processing $argv[$i] ...";
if (!is_file( $argv[$i] ) ) die( "Invalid file: $argv[$i]\n" );
$gpx = file_get_contents( $argv[$i] );
if ( $i == 1 ) preg_match( "/^(.*?)<trkseg>.*?<\/trkseg>(.*?)$/is", $gpx, $metadata );
preg_match("/<trkseg>(.*?)<\/trkseg>/ims", $gpx, $matches);
if( trim( $matches[1] ) )
{
$segments .= $matches[1];
echo "[OK]\n";
}
else
echo "[FAIL]\n";
}
$output_file = $metadata[1] . "<trkseg>" . $segments . "</trkseg>" . $metadata[2];
file_put_contents($argv[sizeof($argv) -1], $output_file) or die( "Unable to create destination GPX\n" );
print "File " . $argv[sizeof($argv) -1] . " successfully created.\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment