1

I was wondering if someone could give me a hand.

I have a KML file (Google Maps XML) and I need to extract the coordinates to a 2D array.

The format of the file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<kml
    xmlns="http://earth.google.com/kml/2.1">
    <Document>
        <Placemark>
            <name>Im a name</name>
            <Point>
                <coordinates>138.611798,-34.926053</coordinates>
            </Point>
        </Placemark>
        <Placemark>
            <name>Im a name</name>
            <Point>
                <coordinates>138.611798,-34.926053</coordinates>
            </Point>
        </Placemark>
        <Placemark>
            <name>Im a name</name>
            <Point>
                <coordinates>138.611798,-34.926053</coordinates>
            </Point>
        </Placemark>
        [...]

I need to be able to return an array with the following format:

Array
(
    [0] => Array
        (
            [0] => 138.611798
            [1] => -34.926053
        )
    [1] => Array
        (
            [0] => 138.611798
            [1] => -34.926053
        )

My KML file will contain quite a few points so I need to be able to do this automatically.

Any help would be really appreciated.

Thanks

Kevin
  • 41,694
  • 12
  • 53
  • 70
BigJobbies
  • 499
  • 8
  • 20

2 Answers2

2

You can use XPath for that. Just don't forget to set namespace.

$xml = simplexml_load_file('kml.xml'); $xml->registerXPathNamespace('ns', 'http://earth.google.com/kml/2.1'); $names = $xml->xpath('//ns:coordinates'); $coordinates = array(); foreach($names as $name) { $coordinates[] = explode( ',', $name ); } print_r( $coordinates );

Valentin Rodygin
  • 864
  • 5
  • 12
1

You could just use SimpleXML to get the desired values and push them inside an array. Example:

$data = array();
$xml = simplexml_load_file('path/to/file.kml');
foreach($xml->Document->Placemark as $placemark) {
    list($x, $y) = explode(',', $placemark->Point->coordinates); // explode coordinates by comma
    $data[] = array($x, $y);
}

echo '<pre>';
print_r($data);

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70