Php简单XML帮助<;gx:cord>;


Php Simple XML Help <gx:coord>

我想回显foreach中的所有"gx:cord"。

这就是我现在拥有的:

# XML
$my_track = new SimpleXMLElement(file_get_contents('track.kml'));

echo $my_track->Document->description;

但是如何在foreach循环中获得gx:cord的值呢?

<Document>
<description>Test</description>
<gx:MultiTrack>
    <altitudeMode>absolute</altitudeMode>
    <gx:interpolate>1</gx:interpolate>
    <gx:Track>
        <when>2012-07-23T15:00:44.000Z</when>
        <gx:coord>2.508616 50.641113 46.0</gx:coord>
        <when>2012-07-23T15:00:44.000Z</when>
        <gx:coord>2.508616 50.641113 46.0</gx:coord>
        <when>2012-07-23T15:00:59.000Z</when>
        <gx:coord>2.508616 50.641113 49.0</gx:coord>
    </gx:Track>
    </gx:MultiTrack>
</Document>

我希望这是foreach的结果:

2.508616 50.641113 46.0
2.508616 50.641113 46.0
2.508616 50.641113 49.0

需要真正的帮助。

<?php
$xml = '<Document>
        <description>Test</description>
        <gx:MultiTrack>
            <altitudeMode>absolute</altitudeMode>
            <gx:interpolate>1</gx:interpolate>
            <gx:Track>
                <when>2012-07-23T15:00:44.000Z</when>
                <gx:coord>2.508616 50.641113 46.0</gx:coord>
                <when>2012-07-23T15:00:44.000Z</when>
                <gx:coord>2.508616 50.641113 46.0</gx:coord>
                <when>2012-07-23T15:00:59.000Z</when>
                <gx:coord>2.508616 50.641113 49.0</gx:coord>
            </gx:Track>
            </gx:MultiTrack>
        </Document>';
$data = simplexml_load_string( $xml );
// Or $data = simplexml_load_file( $filename );
foreach ( $data -> children() -> MultiTrack -> Track -> coord as $value ) {
    echo $value . '<br />';
}
?>

我也遇到了同样的问题,我使用了xpath类似:

$arr = xpath('//gx:coord');

有关更多信息,请查看:

  • http://php.net/manual/en/simplexmlelement.xpath.php

和更多指定的命名空间

  • http://php.net/manual/en/simplexmlelement.registerxpathnamespace.php

如果您得到一个没有名称空间

的文件,这也将有助于解决问题