GPX file parse with PHP, get <extensions> element values

余生颓废 提交于 2021-01-29 04:45:54

问题


i have xml/gpx file:

<?xml version="1.0" encoding="utf-8"?>
<gpx xsi:schemaLocation="http://www.topografix.com/GPX/1/1">
  <metadata>
....
  </metadata>
  <trk>
    <trkseg>
      <trkpt lat="50.04551333333333" lon="14.434101666666667">
        <ele>282</ele>
        <time>2014-06-30T20:56:03.92</time>
        <extensions>
          <gpxtpx:TrackPointExtension>
            <gpxtpx:hr>100</gpxtpx:hr>
          </gpxtpx:TrackPointExtension>
        </extensions>
      </trkpt>
...
</gpx>

Load:

$xml=simplexml_load_file($gpx_file);

parse witch

foreach($xml->trk->trkseg->trkpt as $point){}

Thats fine. But i cant get content of /extension//extension/

print_r($point) is

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [lat] => 50.04527
            [lon] => 14.433993333333333
        )

    [ele] => 280.5
    [time] => 2014-06-30T20:57:21.71
    [extensions] => SimpleXMLElement Object
        (
        )
)

and i cannot get SimpleXMLElement Object.

Print_r($point->extension is:

SimpleXMLElement Object
(
)

I try Converting a SimpleXML Object to an Array and other similiar way, but i have failed - output is empty array.

Any idea/way to get into string/array ?

Sample gpx is on www.vovcinec.net/gpx/e.gpx (~700kB)


回答1:


You can't get them directly since they are in namespaces, you need to use getNamespaces() method first. Consider this example:

$xml = simplexml_load_file('e.gpx');
foreach($xml->trk->trkseg->trkpt as $trkpt) {

    $namespaces = $trkpt->getNamespaces(true);
    $gpxtpx = $trkpt->extensions->children($namespaces['gpxtpx']);
    $hr = (string) $gpxtpx->TrackPointExtension->hr;
    echo '<pre>';
    print_r($hr);
    echo '</pre>';
}



回答2:


I hope you help following code

foreach($gpx->trk->trkseg->children() as $trkpts) {
    echo (string)$trkpts->extensions->children('gpxtpx',true)->TrackPointExtension->hr;
}

no need to use getNamespaces() method



来源:https://stackoverflow.com/questions/24500347/gpx-file-parse-with-php-get-extensions-element-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!