• 0

OSM Overpass API with PHP-SimpleXML :: workin with the the OSM-Endpoint


Question

good day dear programmers, dear experts here at Neowin, 

 

i am currently working on a parser that gets  data via OSM Overpass API with PHP-SimpleXML. I am workin with the pretty new to the work with PHPSimpleXML so do not bear with me for askin newby questions.  I am tryin to get data using Open Street Maps. I want to write a code that works with the endpoint of openstreetmap - and the given data is the starting point for further explorations. My tactic is as follows:

 

I fetch data from the openstreetmap-endpoint 

 

1. i run requests to the openstreetmap-endpoint- (see below) and i try three different APIs per request isn't that easy on ressources and 
2. I don't know how to work with the results that i gather from the OpenStreetmap-Endpoint


see the request: 

 

 

<?php
/**
 * OSM Overpass API with PHP SimpleXML / XPath
 *
 * PHP Version: 5.4 - Can be back-ported to 5.3 by using 5.3 Array-Syntax (not PHP 5.4's square brackets)
 */


//
// 1.) Query an OSM Overpass API Endpoint
//

$query = 'node
  ["amenity"~".*"]
  (38.415938460513274,16.06338500976562,39.52205163048525,17.51220703125);
out;';


This is derived from here: http://stackoverflow.com/questions/16129184/osm-data-parsing-to-get-the-nodes-with-child

I want to filter the data to get the nodes with special category. Here is sample of the OSM data I want to get the whole schools within an area. The first script runs well - but now i want to refine the search and add more tags. Finally i want to store all into the MySQL-db

 

So we need to make some XML parsing with PHP:

The following is a little OSM Overpass API example with PHP SimpleXML

 

 

 

<?php
/**
 * OSM Overpass API with PHP SimpleXML / XPath
 *
 * PHP Version: 5.4 - Can be back-ported to 5.3 by using 5.3 Array-Syntax (not PHP 5.4's square brackets)
 */

//
// 1.) Query an OSM Overpass API Endpoint
//

$query = 'node
  ["amenity"~".*"]
  (38.415938460513274,16.06338500976562,39.52205163048525,17.51220703125);
out;';

$context = stream_context_create(['http' => [
    'method'  => 'POST',
    'header' => ['Content-Type: application/x-www-form-urlencoded'],
    'content' => 'data=' . urlencode($query),
]]);

# please do not stress this service, this example is for demonstration purposes only.
$endpoint = 'http://overpass-api.de/api/interpreter';
libxml_set_streams_context($context);
$start = microtime(true);

$result = simplexml_load_file($endpoint);
printf("Query returned %2\$d node(s) and took %1\$.5f seconds.\n\n", microtime(true) - $start, count($result->node));

//
// 2.) Work with the XML Result
//

# get all school nodes with xpath
$xpath = '//node[tag[@k = "amenity" and @v = "school"]]';
$schools = $result->xpath($xpath);
printf("%d School(s) found:\n", count($schools));
foreach ($schools as $index => $school)
{
    # Get the name of the school (if any), again with xpath
    list($name) = $school->xpath('tag[@k = "name"]/@v') + ['(unnamed)'];
    printf("#%02d: ID:%' -10s  [%s,%s]  %s\n", $index, $school['id'], $school['lat'], $school['lon'], $name);
}

?>

 

The second part is more interesting. That is querying the XML data you have already. This is most easily done with xpath, the used PHP XML library is based on libxml which supports XPath 1.0 which covers the various querying needs very well. The following example lists all schools and tries to obtain their names as well. I have not covered translations yet because my sample data didn't have those, but you can also look for all kind of names including translations and just prefer a specific one):

The key point here are the xpath queries. Two are used, the first one to get the nodes that have certain tags. I think this is the most interesting one for you:

 

//node[tag[@k = "amenity" and @v = "school"]]

 

This line says: Give me all node elements that have a tag element inside which has the k attribute value "amenity" and the v attribute value "school". This is the condition you have to filter out those nodes that are tagged with amenity school. Further on xpath is used again, now relative to those school nodes to see if there is a name and if so to fetch it:

 

tag[@k = "name"]/@v'

 

This line says: Relative to the current node, give me the v attribute from a tag element that as the k attribute value "name". As you can see, some parts are again similar to the line before. I think you can both adopt them to your needs. Because not all school nodes have a name, a default string is provided for display purposes by adding it to the (then empty) result array:

 

list($name) = $school->xpath('tag[@k = "name"]/@v') + ['(unnamed)'];
                                                    ^^^^^^^^^^^^^^^
                                                Provide Default Value

so far so good: note. i need to have the adress-data, of the school with

 

cf http://wiki.openstreetmap.org/wiki/Key:addr

and even more important

cf http://wiki.openstreetmap.org/wiki/Key:contact

 

  Quote

contact:phone 
contact:fax     
contact:website 
contact:email

Expand  

 

btw. here my results for that code-example:

 

 

 

martin@linux-70ce:~/php> 
martin@linux-70ce:~/php> php osm1.php
Query returned 1691 node(s) and took 3.34569 seconds.

23 School(s) found:
#00: ID:332534486   [39.5017565,16.2721899]  Scuola Primaria
#01: ID:1428094278  [39.3320912,16.1862820]  (unnamed)
#02: ID:1822746784  [38.9075566,16.5776597]  (unnamed)
#03: ID:1822755951  [38.9120272,16.5713431]  (unnamed)
#04: ID:1903859699  [38.6830409,16.5522243]  Liceo Scientifico Statale A. Guarasci
#05: ID:2002566438  [39.1349460,16.0736446]  (unnamed)
#06: ID:2056891127  [39.4106679,16.8254844]  (unnamed)
#07: ID:2056892999  [39.4124687,16.8286119]  (unnamed)
#08: ID:2272010226  [39.4481717,16.2894353]  SCUOLA DELL'INFANZIA SAN FRANCESCO
#09: ID:2272017152  [39.4502366,16.2807664]  Scuola Media
#10: ID:2358307794  [39.5015031,16.3905965]  I.I.S.S. Liceo Statale V. Iulia
#11: ID:2358307796  [39.4926280,16.3853662]  Liceo Classico
#12: ID:2358307797  [39.4973761,16.3858275]  Scuola Media
#13: ID:2358307800  [39.5015527,16.3941156]  I.T.C. e per Geometri
#14: ID:2358307801  [39.4983862,16.3807796]  Istituto Professionale
#15: ID:2358344885  [39.4854617,16.3832419]  Istituto Tecnico Statale Commerciale G. Falcone
martin@linux-70ce:~/php>

 

note. i need to have the adress-data, of the shool with

and even more important http://wiki.openstreetmap.org/wiki/Key:contact

 

  Quote

contact:phone 
contact:fax     
contact:website 
contact:email
 

Expand  

 

How to add this .. into the query? and how to finally store all into the MySQL-db?

update: can i rework like so:

 

 

 

$xml = file_get_contents($url);
$data = new SimpleXMLElement($xml);

$data variable contains the following:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [timestamp] => Sat, 15 Jun 13 20:02:13 +0000
            [attribution] => Data Š OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
            [querystring] => Bucharest-Romania
            [polygon] => false
            [exclude_place_ids] => 331526
            [more_url] => http://nominatim.openstreetmap.org/search?format=xml&exclude_place_ids=331526&q=Bucharest-Romania
        )

    [place] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [place_id] => 331526
                    [osm_type] => node
                    [osm_id] => 96209423
                    [place_rank] => 15
                    [boundingbox] => 44.4361381530762,44.4361419677734,26.1027431488037,26.1027450561523
                    [lat] => 44.436139
                    [lon] => 26.1027436
                    [display_name] => BucureČti, Sector 2, Bucuresti, România, European Union
                    [class] => place
                    [type] => city
                    [importance] => 0.73231672860554
                    [icon] => http://nominatim.openstreetmap.org/images/mapicons/poi_place_city.p.20.png
                )

        )

)

 

 

dear friends, look forward to hear from you

 

 

Edited by tarifa

3 answers to this question

Recommended Posts

  • 0

good day dear +Human.Online, 

 

 

first of all: many thanks for the quick reply. glad to hear from you.  Sure thing - there are various forums out there that are centered and focused on topics like 

 

- OpenStreetmap

- Geospatial-topics

- PHP-forums - with expertise on topics such als Xpath topics and XML-parser 

- Linux-forums that cover all the above topics alltogehter

 

- on a sidenote: i am pretty new to this forum here - but i encountered this forum as being capable to cover all computer-topics - 

so as of now - (with experience of 117 postings) i treat this forum as a one stop contact point - for all computer-things

 

but probably i am wrong with this idea and hypothesis or praxis!? - perhaps i cannot treat this forum as such .... 

 

above all - i love this place as a place for idea sharing and knowledge exchange - generally spoken - for being a universe of discourse for all computer  things.. 

 

generally spoken:  i love this forum for its people that fuel all the discourse and idea exchange. 

 

many thanks for your continued support. + Human.Online

 

 

have a great day 

- Tarifa ;)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I would love to see Musk's face! 🤣🤣🤣
    • I think each AI option has their ups and downs. For Copilot, I find it more personable in how it talks compared to GPT & Gemini. I also appreciate the open ended questions it often provides at the end of its responses to keep the conversation going.
    • Microsoft offers free access to AI video creation with Bing Video Creator by Pradeep Viswanathan Two years ago, Bing Image Creator became one of the first major online services that allowed users to create images from text using OpenAI’s DALL-E model. Today, Microsoft is introducing Bing Video Creator, powered by OpenAI’s Sora, allowing users to create videos with text prompts. Despite announcing Sora last year, OpenAI has not been able to expand its availability to millions of ChatGPT users due to huge AI infrastructure requirements. It is still only available to ChatGPT Pro subscription users, which costs about $200 per month. Recently, Google announced its Veo 3 video generation model, which performs significantly better than OpenAI’s Sora, to all Gemini paid subscribers, making video generation accessible to even Gemini Pro subscribers, which costs just $20 per month. Now, Microsoft is democratizing access to video generation models by making Bing Video Creator free for all Bing users. Bing Video Creator is rolling out today globally (excluding China and Russia) on the Bing Mobile App, and it will be coming soon to the Bing desktop experience within Copilot Search. Bing Video Creator users will have the ability to choose between Fast and Standard generation speeds. Each user will have 10 Fast creations; following that, users can redeem 100 Microsoft Rewards points for each Fast creation or continue with Standard creation speeds. Once you have downloaded the Bing mobile app, here’s how you can access the Video Creator feature: Open Video Creator within the Bing Mobile app by clicking on the menu in the bottom right corner and selecting “Video Creator.” Just type in a text description of the video you want to create in the prompt box. Once the prompt text is ready, just tap “Create.” Or you can also just type directly into the Bing mobile app search bar "Create a video of..." to create a video. You’ll receive a notification when your video is ready to view. If required, you can also download the video or share it via social media or email. You will also have the ability to copy a direct link to the video for easy sharing elsewhere. Microsoft will be storing the generated videos for up to 90 days in your account for easy access later. Microsoft noted that the Bing Video Creator videos are 5 seconds long and can be created only in 9:16 format for now. Microsoft will be adding the 16:9 format soon. When you are waiting for your video to be created, you can also queue up another two videos. Once one of the slots becomes available, you can add another one to the queue. When Bing Video Creator becomes available on desktop, you can visit Bing.com/create for both image and video creation needs.
    • AMD 9060 XT performance benchmarks vs Nvidia 5060 Ti, 5060, AMD 9070 XT, 7600 XT, leaks by Sayan Sen AMD is preparing to launch the RX 9060 XT next and it will be available in two variants, one with 16 GB VRAM and another with half of that at 8 GB. The company publicly defended the latter explaining how it felt there is still a huge market for it as many users do not actually need more than that. We recently wrapped up our review of the AMD Radeon 9070 series with the RX 9070 scoring a 9 out of 10 for AI testing and 7.5 out of 10 in gaming. If you read our reviews you will see that the performance of the is decent for the price but it is definitely more efficient than its XT counterpart. Thus we already have a fairly good idea of how it performs. With the RX 9060 XT launch scheduled for June 5 later this week, reviewers are starting to test the GPU. As such, one such review has accidentally leaked early and it has revealed the performance of the RX 9060 XT variant against the likes of AMD's own 9070 series, 7700 XT, 7600 XT, as well as Nvidia's RTX 5060 Ti, 5060, and more. On average at 1440p, the 9060 XT 16 GB model appears to be a bit slower than the 7700 XT as well as Nvidia's 5060 Ti 16GB. Interestingly though the Radeon GPU does seem to be offering better minimums so maybe we could see a smoother gaming experience overall despite a lower average. AMD says that it is expecting better than 5060 Ti 8GB performance with the 9060 XT 16 GB. The former has an MSRP of $379 while the latter is priced $349. Versus the $299 GeForce 5060 (8GB), the 9060 XT 16 GB is about 10% better but the minimums are a whopping 43% higher. AMD's 9060 XT is also showing excellent performance in case of ray tracing (RT) as you can see in Cyberpunk 2077 above where it is giving comparable throughput as the 7800 XT and is miles better than its preceeding 7600 XT with 63% boost. We see a similar situation in Black Myth: Wukong as well which is another RT heavy game. To understand how AMD achieved the ray tracing gains on RDNA 4, you can read our architecture overview article here. Source and images: BasedDaemonTargaryen (Reddit)
  • Recent Achievements

    • Week One Done
      Nullun earned a badge
      Week One Done
    • First Post
      sultangris earned a badge
      First Post
    • Reacting Well
      sultangris earned a badge
      Reacting Well
    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      149
    2. 2
      Xenon
      122
    3. 3
      ATLien_0
      122
    4. 4
      snowy owl
      99
    5. 5
      +Edouard
      95
  • Tell a friend

    Love Neowin? Tell a friend!