User:Tagtheworld/SimpleXMLElement::xpath
Jump to navigation
Jump to search
SimpleXMLElement::xpath
derived from a very interesting threadː http://stackoverflow.com/questions/30316371/extracting-data-from-osm-xml-file-with-php
stackoverflow user har07 notesː
You can use SimpleXMLElement::xpath to get both "via" and the corresponding "idnode" values. For example :
$raw = <<<EOF
<root>
<way id="28747493" visible="true" version="7" changeset="9347177" timestamp="2011-09-19T21:48:11Z" user="Camilo Alvarez" uid="492132">
<nd ref="316077528"/>
<nd ref="316077503"/>
<tag k="highway" v="primary"/>
<tag k="lanes" v="1"/>
<tag k="name" v="Calle 51"/>
<tag k="oneway" v="yes"/>
<tag k="ref" v="Boyacá"/>
</way>
<way id="28747492" visible="true" version="9" changeset="7227086" timestamp="2011-02-08T15:33:22Z" user="dmartinh" uid="314700">
<nd ref="358031212"/>
<nd ref="316077505"/>
<tag k="foot" v="permissive"/>
<tag k="highway" v="footway"/>
<tag k="name" v="Calle 52"/>
</way>
</root>
EOF;
$xml = simplexml_load_string($raw);
foreach($xml->xpath("//way") AS $way){
$via = $way->xpath("tag[@k='name']/@v")[0];
foreach($way->nd AS $nd){
$idnode = $nd["ref"];
echo $idnode .", ". $via ."<br>";
}
}
Demo
output :
316077528, Calle 51
316077503, Calle 51
358031212, Calle 52
316077505, Calle 52
xpath explanation:
//way selects all <way> elements anywhere in the XML document.
tag[@k='name'] selects <tag> child of current context node having k attribute value equal name. Then from that <tag>, /@v returns v attribute.
thanks to stackoverflow user har07 - cf http://stackoverflow.com/questions/30316371/extracting-data-from-osm-xml-file-with-php