在PHP中将KML转换为数组

时间:2017-07-07 19:03:13

标签: php kml

当我尝试使用*.kml语言将PHP文件转换为数组时,我遇到了困难。

kml档案>> path.kml

    $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);

问题是当我试图使用newLine分隔符爆炸字符串时,结果始终如下所示 enter image description here

虽然我想要这样的结果enter image description here 谁能帮助我解决我的问题吗?谢谢!

3 个答案:

答案 0 :(得分:1)

'\r\n' (单引号之间)是: - 字面反斜杠,字母r,字面反斜杠和字母n。它不是回车和换行。在单引号之间,不解释转义序列。

其他事项:你确定新行序列是CRLF吗?它也可以只是LF(很少只有CR)。

无论如何,请尝试使用"\r\n",如果它不适用于"\n" (双引号之间)

About PHP strings.

答案 1 :(得分:0)

有不同的换行符,而不仅仅是\r\n - 尝试使用类似preg_split ('/\R/', $string);的内容来捕捉所有换行符。

有关\R的详细解释,请查看this SO回答。

答案 2 :(得分:0)

你可以修剪coords数组:

<?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);

但关于行终止符的其他答案的考虑是正确的,我使用了来自other SO question的正则表达式。