使用SimpleXML解析Garmin GPX XML数据

时间:2017-03-18 08:19:06

标签: php xml simplexml gpx

我有这个GPX文件:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" .. >
    <metadata>
        <link href="http://www.garmin.com">
            <text>Garmin International</text>
        </link>
        <time>2017-03-13T14:42:05Z</time>
    </metadata>
    <trk>
        <name>2017-03-13 15:41:57</name>
        <extensions>
            <gpxx:TrackExtension>
                <gpxx:DisplayColor>Cyan</gpxx:DisplayColor>
            </gpxx:TrackExtension>
            <gpxtrkx:TrackStatsExtension>
                <gpxtrkx:Distance>6482</gpxtrkx:Distance>
                <gpxtrkx:MovingTime>4474</gpxtrkx:TimerTime>
            </gpxtrkx:TrackStatsExtension>
        </extensions>
        <trkseg>
            <trkpt lat="47.1075830329" lon="15.4409365822">
                <ele>466.49</ele>
                <time>2017-03-13T13:26:10Z</time>
            </trkpt>
            <trkpt lat="47.1075813565" lon="15.4409420304">
                <ele>466.49</ele>
                <time>2017-03-13T13:26:11Z</time>
            </trkpt>
            ...
        </trkseg>
    </trk>
</gpx>

我想用SimpleXML解析它,但无法访问TrackStatsExtension。 我如何遍历TrackStatsExtension - 获取距离和移动时间?

我想计算平均速度。

2 个答案:

答案 0 :(得分:2)

好的,我自己发现了:

$xml = simplexml_load_file($file);
$namespaces = $xml->trk->getNamespaces(true);
$ext = $xml->trk->extensions->children($namespaces['gpxtrkx']);
$Distance = $ext->TrackStatsExtension->Distance ;
$MovingTime = $ext->TrackStatsExtension->MovingTime ;
$Speed = $Distance / $MovingTime * 3.6 ;

DEFINE ( 'NL', '<br />' ) ;
echo '--------------------' . NL ;
echo 'Distance    : ' . $Distance . ' m' . NL ;
echo 'MovingTime  : ' . $MovingTime . ' s' . NL ;
echo 'Avg speed   : ' . round ( $Speed, 2 ) . ' km/h'. NL ;
echo '--------------------' . NL ;

答案 1 :(得分:0)

你犯了一个简单的错误:

<gpxtrkx:MovingTime>4474</gpxtrkx:TimerTime>

<gpxtrkx:MovingTime>4474</gpxtrkx:MovingTime>

你也可以使用:

<gpxtrkx:MovingTime>4474</gpxtrkx:MovingTime>
<gpxtrkx:TimerTime>4474</gpxtrkx:TimerTime>
<gpxtrkx:TotalElapsedTime>4474</gpxtrkx:TotalElapsedTime>