Search code examples
phpkml

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!


Solution

  • '\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.