Last active
July 6, 2016 23:40
-
-
Save nimmneun/318c37a855c9ffbab81f381a9427f606 to your computer and use it in GitHub Desktop.
openstreetmap nodes die einen bestimmten suchstring enthalten in neues file schreiben
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class OsmNodeParser | |
{ | |
private $spl; | |
private $current; | |
private $isOpen = false; | |
private $hasQuery = false; | |
private $nodes = []; | |
public function __construct($path) | |
{ | |
$this->spl = new SplFileObject($path, 'r'); | |
} | |
public function findNodesWith($query = 'housenumber') | |
{ | |
while ($line = $this->spl->fgets()) { | |
$this->findNodeData(trim($line), $query); | |
} | |
$xml = '<?xml version="1.0" encoding="utf-8"?>'; | |
$xml .= '<nodes>' . PHP_EOL; | |
$xml .= implode($this->nodes); | |
$xml .= '</nodes>'; | |
simplexml_load_string($xml)->asXML('nodes.xml'); | |
echo PHP_EOL . count($this->nodes) . ' nodes gefunden' . PHP_EOL; | |
} | |
/** | |
* @param string $line | |
* @param string $query | |
*/ | |
private function findNodeData($line, $query) | |
{ | |
if (0 === strpos($line, '<node ') && substr($line, -2) == '/>') { | |
// direkt weiter wenns ein self closing node tag ist | |
return; | |
} elseif (0 === strpos($line, '<node ')) { | |
// node open tag festhalten | |
$this->current .= ' ' . $line . PHP_EOL; | |
$this->isOpen = true; | |
} elseif ($this->isOpen && 0 === strpos($line, '</node>')) { | |
// bei node close tag, node festhalten wenn query zuvor gefunden | |
if ($this->hasQuery) { | |
$this->nodes[] = $this->current . ' ' . $line . PHP_EOL; | |
} | |
$this->reset(); | |
} elseif ($this->isOpen) { | |
// alles nach node open und vor node close tag festhalten | |
$this->current .= ' ' . $line . PHP_EOL; | |
if (false !== strpos($line, $query)) { | |
$this->hasQuery = true; | |
} | |
} | |
} | |
/** | |
* Nach schießendem node tag alles wieder zurücksetzen. | |
*/ | |
public function reset() | |
{ | |
$this->isOpen = $this->hasQuery = false; | |
$this->current = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment