Bhazk
Bhazk

Reputation: 221

Converting KML to Array in PHP

I've got stuck when i'm trying to convert a *.kml file to array using PHP language.

kml file >> path.kml

code

    $dom = new \DOMDocument();
    $dom->loadXml($file);
    $xpath = new \DOMXPath($dom);
    $xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

    $result = array();
    $places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
    foreach ($places as $place) {
        $coord = $xpath->evaluate('string(kml:LineString/kml:coordinates)',$place, FALSE);
        $i = explode("\n", $coord);
        $result = array(
            'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
            'coords' => explode("\n", $coord, count($i)
            )
        );
    }

    var_dump($result);

the problem is when i'm trying to explode the string using newLine delimeter, and the result is always like this
enter image description here

whereas i want the result like this enter image description here
could anyone to help me for solve my problem ? Thank You!

Upvotes: 2

Views: 1211

Answers (3)

Holzhey
Holzhey

Reputation: 381

You can trim the coords array:

<?php

function itemTrim(&$item) {
    $item = trim($item);
}

$r = "
     115.09031667,-8.81930500,64.500
     115.09031500,-8.81925667,64.400
     115.09033000,-8.81920167,64.300
     115.09038167,-8.81911333,64.100
     115.09042333,-8.81904000,64.000
     115.09048000,-8.81896833,63.900
     115.09053333,-8.81889167,63.800
     115.09056167,-8.81882333,63.800
     115.09059500,-8.81876667,63.800
     115.09063500,-8.81872500,63.900
     115.09067333,-8.81870167,63.800
    ";

$a = preg_split("/\r\n|\n|\r/", $r);
$b = array_walk($a, "itemTrim");

var_dump($a);

But the considerations on the other answers about the line terminator is true, i used an regular expression from other SO question.

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

'\r\n' (between single quotes) is: - a literal backslash, the letter r, a literal backslash, and the letter n. It isn't a carriage return and a linefeed. Between single quotes, escape sequences are not interpreted.

Other thing: Are you sure that the newline sequence is CRLF? It can be also only LF (rarely only CR).

Whatever, Try with "\r\n" and if it doesn't work with "\n" (between double quotes).

About PHP strings.

Upvotes: 1

Laura
Laura

Reputation: 3383

There is different new line characters, not just \r\n - try using something like preg_split ('/\R/', $string); instead to catch all new line characters.

For a more detailed explanation of what \R does, check out this SO answer.

Upvotes: 0

Related Questions