Ankündigung

Einklappen
Keine Ankündigung bisher.

osm-xpath Abrrage mit PHP simpleXML

Einklappen

Neue Werbung 2019

Einklappen
X
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

  • osm-xpath Abrrage mit PHP simpleXML

    hallo und guten Abend

    bin neu in diesem Forum - und auch relativ neu in PHP. Also was ich grade vorhabe ist
    eine openstreetmap-Abfrage mittels overpass-Api zu stellen.

    Kenn mich mit xpath u. DOM noch nicht so gut aus - hab heute mittag mal die xpath-Dokus gelesen und auch jene zu simpleXML

    hier was schon mal geht....


    PHP-Code:
    <?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) - $startcount($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);
    }
    xpath Abfragen

    zwei sind dort oben gebraucht eine xpath query sieht nacher den nodes die einen bestimmten tag haben


    das hier

    Code:
    //node[tag[@k = "amenity" and @v = "school"]]
    gib uns alle Elements die ein tag element drinne haben wie zb. das k attribute - value "amenity" und das v attribute mit dem Wert "school".
    Damit werden aus den og. Nodes alle jene ausgefiltert die die amenity school haben


    dann wird xpath weiter genutzt, jetzt um all die school nodes um zu sehen ob da ein name drinne ist - und um diesen zu holen :

    Code:
    tag[@k = "name"]/@v'
    Relative zu diesem node, gib mir das v attribut des tag elements mit dem k attribute value "name".

    weil nicht alle Schulen einen namen haben , wird noch ein default string angehängt . um auch namenlose schulen ins array zu laden.:

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


    2179 School(s) found: the last ones are shown below.....

    #2151: ID:2688357765 [51.4668941,-0.9731135] New Directrions, North Reading
    #2152: ID:2702504696 [51.5884265,-0.7829013] Burford School
    #2153: ID:2702549737 [51.5802201,-0.7653918] Great Marlow School
    #2154: ID:2706219304 [51.3779317,-0.0895302] ARK Oval Primary Academy
    #2155: ID:2706219314 [51.3871935,-0.0623001] Ashburton Primary School
    #2156: ID:2706219320 [51.3210977,-0.1398859] CALAT Smitham Centre
    #2157: ID:2706219326 [51.3638861,-0.0922032] Elmhurst School
    #2158: ID:2706219339 [51.4007121,-0.0743710] Harris Academy South Norwood
    #2159: ID:2706219343 [51.3831662,-0.0405476] Orchard Way Primary School
    #2160: ID:2706219347 [51.3531047,-0.0959447] Purley Oaks Primary School
    #2161: ID:2706219348 [51.3428384,-0.0069931] Rowdown Primary School
    #2162: ID:2706219350 [51.3954917,-0.0732185] South Norwood Primary School
    #2163: ID:2706219351 [51.3377151,-0.1230482] St David's Preparatory School
    #2164: ID:2706219353 [51.3993760,-0.1144352] Winterbourne School
    #2165: ID:2717394621 [51.8706538,0.1480886] Prep
    #2166: ID:2717394636 [51.8685838,0.1463720] Pre-Prep
    #2167: ID:2722704201 [51.1398429,-0.0457445] Felbridge Primary School

    nun will ich noch mehr xpath -anfragen einbauen in die loop entsprechend Key:contact - OpenStreetMap Wiki

    contacthone
    contact:fax
    contact:website
    contact:email
    also - die von mir versuchten erweiterungen der xpath Abfrage in der Loop sind gescheitert... Kann jeamdn weiterhelfen.

    freu mich auf eine Antwort...

  • #2
    Wie sieht denn dein bisheriger Ansatz aus?

    Kommentar


    • #3
      hallo und guten Abend rkr


      Zitat von rkr Beitrag anzeigen
      Wie sieht denn dein bisheriger Ansatz aus?

      habe versucht in die loop eine erweiterte Abfrage einzubauen. .... auf zwei verschiedenen wegen:


      PHP-Code:
        
          
      list($website) = $school->xpath ('tag[@k = "website"]/@v'):
          list(
      $email) = $school->xpath ('tag[@k = "email"]/@v'); 
      und auf diesem wege:
      PHP-Code:
       list($name) = $school->xpath ('tag[@k = "name"]/@v','tag[@k = "website"]/@v','tag[@k = "email"]/@v') + ['(unnamed)']; 
      - also beides hat nicht funktioniert...

      PHP-Code:
      2 School(sfound:
      PHP Warning:  SimpleXMLElement::xpath() expects exactly 1 parameter3 given in /home/martin/php/osm6.php on line 57
      PHP Fatal error
      :  Unsupported operand types in /home/martin/php/osm6.php on line 57
      martin
      @linux-70ce:~/phpphp osm6.php 

      wäre um einen tipp dankbar...

      gruss dilbert

      update:



      also was ich mir noch überlegt habe ist folgendes:

      ich koennte noch alle elemente in dem xml überhaupt mal anshenen...

      etwa so:

      PHP-Code:
          echo "<pre>";
          
      var_dump($result);
          echo 
      "</pre>"
      weiterhin hab ich mir noch überlegt das hier einzusetzen;:


      PHP-Code:
          
      <?php
              $xmldoc 
      = new DOMDocument();
              
      $xmldoc->load('sample.xml');

              
      $xpathvar = new Domxpath($xmldoc);

              
      $queryResult $xpathvar->query('//');
              foreach(
      $queryResult as $result){
                      echo 
      $result->textContent;
        
        
        }
      ?>
      was meinst du denn dazu - ich wollte halt mal sehen ob ich ggf weiterkomme mit DOM

      Kommentar


      • #4
        PHP-Code:
        //tag[@attr="content" or @attr="content" or @attr="content"] 

        Kommentar


        • #5
          Gib hier mal an was dein XPATH bewirken soll ( was du genau selektieren willst ) und eine portion (beispiel-)xml zum nachvollziehen.

          Bedenke das Path-Angaben in xpath ohne path-elevation ( / ) im aktuellen Node durchgeführt werden ( und nur da ).
          [URL="https://gitter.im/php-de/chat?utm_source=share-link&utm_medium=link&utm_campaign=share-link"]PHP.de Gitter.im Chat[/URL] - [URL="https://raindrop.io/user/32178"]Meine öffentlichen Bookmarks[/URL] ← Ich habe dir geholfen ? [B][URL="https://www.amazon.de/gp/wishlist/348FHGUZWTNL0"]Beschenk mich[/URL][/B].

          Kommentar


          • #6
            hallo rkr hallo trOy


            update; hab mal ganz oben im Threadstart den code ergänzt und die Abfrage am overpass-api-endpunkt noch näher beschrieben. So gehts schonmal. Allerdings halt noch mit nur lediglich zwei Tags - oder den folgenden

            id
            lon
            lat
            school-name

            und da wollte ich halt noch ein paar mehr Daten.

            Vorweg: vielen dank für Eure schnellen Antworten. Die sind super und schon sehr wertvolle anregungen. Bin schon seit ein paar Std. an dem Problem dran.


            Zitat von tr0y Beitrag anzeigen
            Gib hier mal an was dein XPATH bewirken soll ( was du genau selektieren willst ) und eine portion (beispiel-)xml zum nachvollziehen. Bedenke das Path-Angaben in xpath ohne path-elevation ( / ) im aktuellen Node durchgeführt werden ( und nur da ).
            Danke!!

            Das sind hilfreiche u. gute Ansätze hier weiterzukommen. Also um rauszukriegen welche tags drinne sind koennte man ja auch so vorgehen:

            Code:
                echo "<pre>";
                var_dump($result);
                echo "</pre>";

            Also - das denke ich geht ja auch in deine Richtung. man müsste ggf einach mal evaluieren was in dem grade abgefragten File so drinne ist. Frage: kann man nicht einach alle Tags holen...


            Grundsätlich hab ich das verstanden: Man sieht die k tags und die Werte (values im OpenStreetMap Export-File
            Die grundsätzliche Struktur <node><tag /></node> unterscheidet die Daten durch Tag’s k Attribut u. die Werte value:



            also grundsätzlich denke ich dass die Mapper unterschiedlich mappen und die Nomenklatur (nominations ) auch etwas unterschiedlich sind.
            GGF werden in Europa noch mehr Daten in den OSM-File aufgenommen

            dann denke ich dass die Unterschiede auch hier dokumentiert sind:

            http://spatial.ucd.ie/lod/osn/page/t...enity/v:school
            http://wiki.openstreetmap.org/wiki/D...enity%3Dschool


            und hier mal ein Bspi - nicht aus dem obigen Code-schnippsel

            Code:
                >> -----------------------------------------------------------------
            >>                      Small Input File
            >> -----------------------------------------------------------------
            <osm version="0.6" generator="osm-extract.pl">
                   <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                   uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                      lon="-70.7561527">
                       <tag k="gnis:created" v="08/27/2002"/>
                      <tag k="gnis:county_id" v="023"/>
                      <tag k="name" v="Wayland Middle School"/>
                      <tag k="amenity" v="school"/>
                       <tag k="gnis:feature_id" v="602607"/>
                       <tag k="gnis:state_id" v="25"/>
                       <tag k="ele" v="34"/>
            	  <tag k="website" v="xyz.org"/>
             
             </node>
            
                   <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                      uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                       lon="-70.7561527">
                       <tag k="gnis:created" v="08/27/2002"/>
                       <tag k="gnis:county_id" v="023"/>
                       <tag k="name" v="Scituate Center Central School"/>
                       <tag k="amenity" v="school"/>
                       <tag k="gnis:feature_id" v="602607"/>
                       <tag k="gnis:state_id" v="25"/>
                       <tag k="ele" v="34"/>
                     <tag k="website" v="xyz.org"/>
             
                   </node>
                   <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                       uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                       lon="-70.7561527">
                       <tag k="gnis:created" v="08/27/2002"/>
                       <tag k="gnis:county_id" v="023"/>
                       <tag k="name" v="Walnut Hill School for the Arts"/>
                       <tag k="amenity" v="school"/>
                       <tag k="gnis:feature_id" v="602607"/>
                       <tag k="gnis:state_id" v="25"/>
                       <tag k="ele" v="34"/>
                       <tag k="website" v="xyz.org"/>
             
             </node>
             </osm>
            Frage - kann man denn nicht eigentlich alle Attribute - by default - holen und dann diejenigen dann die keine WERTE haben
            dann einfach offen lassen.

            - Anm. Am Ende soll doch alles in einer DB gespeichert werden.

            Freu mich auf einen Tipp .

            dilbert

            werde jetzt nochmals die Manpages durchsehen:
            php.net/manual/de/book.simplexml.php

            Kommentar


            • #7
              Ich poste dir das ca. morgen vormittag im Detail. ( wenn niemand anderes sich daran versucht hat )
              [URL="https://gitter.im/php-de/chat?utm_source=share-link&utm_medium=link&utm_campaign=share-link"]PHP.de Gitter.im Chat[/URL] - [URL="https://raindrop.io/user/32178"]Meine öffentlichen Bookmarks[/URL] ← Ich habe dir geholfen ? [B][URL="https://www.amazon.de/gp/wishlist/348FHGUZWTNL0"]Beschenk mich[/URL][/B].

              Kommentar


              • #8
                guren Abend tr0y

                vielen Dank für deine neuerlche Antwort

                Zitat von tr0y Beitrag anzeigen
                Ich poste dir das ca. morgen vormittag im Detail. ( wenn niemand anderes sich daran versucht hat )
                Freu mich schon. Du hast gesehen dass ich hier festhänge. Mit deinen Tipps u. Anregungen komm ich sicher weiter. Freu mich schon.

                Dir mogen einen tollen Wochenstart.

                LG Dilbert

                Kommentar


                • #9
                  Das was du willst ist so am einfachsten:

                  PHP-Code:
                  <?php

                  $xml 
                  = <<<XML
                  <?xml version="1.0" encoding="utf-8"?>
                  <osm version="0.6" generator="osm-extract.pl">
                         <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                         uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                            lon="-70.7561527">
                             <tag k="gnis:created" v="08/27/2002"/>
                            <tag k="gnis:county_id" v="023"/>
                            <tag k="name" v="Wayland Middle School"/>
                            <tag k="amenity" v="school"/>
                             <tag k="gnis:feature_id" v="602607"/>
                             <tag k="gnis:state_id" v="25"/>
                             <tag k="ele" v="34"/>
                        <tag k="website" v="xyz.org"/>
                   
                   </node>

                         <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                            uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                             lon="-70.7561527">
                             <tag k="gnis:created" v="08/27/2002"/>
                             <tag k="gnis:county_id" v="023"/>
                             <tag k="name" v="Scituate Center Central School"/>
                             <tag k="amenity" v="school"/>
                             <tag k="gnis:feature_id" v="602607"/>
                             <tag k="gnis:state_id" v="25"/>
                             <tag k="ele" v="34"/>
                           <tag k="website" v="xyz.org"/>
                   
                         </node>
                         <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                             uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                             lon="-70.7561527">
                             <tag k="gnis:created" v="08/27/2002"/>
                             <tag k="gnis:county_id" v="023"/>
                             <tag k="name" v="Walnut Hill School for the Arts"/>
                             <tag k="amenity" v="school"/>
                             <tag k="gnis:feature_id" v="602607"/>
                             <tag k="gnis:state_id" v="25"/>
                             <tag k="ele" v="34"/>
                             <tag k="website" v="xyz.org"/>
                   
                   </node>
                   </osm>
                  XML;

                  $dom = new DOMDocument();
                  $dom->loadxml($xml);

                  $xpath = new DOMXPath($dom);

                  // select node-tags where subnode tags property k is amenity and subnode tags property v is school

                  $result $xpath->query("node[tag/@k='amenity' and tag/@v='school']"$dom->documentElement);

                  // parse result, execute a closure on every found element
                  $data array_map(function(DOMElement $element) {
                      
                  // filter out all child nodes that are not instances of DOMElement-Class
                      
                  $filtered array_filter(iterator_to_array($element->childNodes), function($inbound) {
                          return 
                  $inbound instanceof DOMElement;
                      });

                      
                  // parse child nodes, execute a closure on every element that matches our previous filter
                      
                  $mapping array_map(function(DOMElement $child) {

                          
                  // create a array entry with k-attribute as key and v-attribute as value and return it.
                          
                  $data = array(
                              
                  $child->getAttribute('k') => $child->getAttribute('v')
                          );

                          return 
                  $data;
                      }, 
                  $filtered);

                      
                  // convert attributes to an array
                      
                  $attributes iterator_to_array($element->attributes);
                      
                  $attributes array_map(function(DOMAttr $attribute) {
                          return 
                  $attribute->nodeValue;
                      }, 
                  $attributes);

                      
                  // merge all sub arrays to one array level and attach it as school-entry to the attributes
                      
                  $attributes['school'] = call_user_func_array('array_merge'$mapping);

                      return 
                  $attributes;
                  }, 
                  iterator_to_array($result));

                  // done.
                  var_dump($data);
                  Wenn du willst kann ich dir auch ein simplexml-Äquivalent posten.

                  Das Ergebnis des obigen Codes:
                  Code:
                  array(3) {
                    [0]=>
                    array(9) {
                      ["id"]=>
                      string(9) "358264143"
                      ["version"]=>
                      string(1) "1"
                      ["timestamp"]=>
                      string(20) "2009-03-10T04:54:34Z"
                      ["uid"]=>
                      string(4) "4732"
                      ["user"]=>
                      string(7) "iandees"
                      ["changeset"]=>
                      string(6) "774950"
                      ["lat"]=>
                      string(10) "42.2017681"
                      ["lon"]=>
                      string(11) "-70.7561527"
                      ["school"]=>
                      array(8) {
                        ["gnis:created"]=>
                        string(10) "08/27/2002"
                        ["gnis:county_id"]=>
                        string(3) "023"
                        ["name"]=>
                        string(21) "Wayland Middle School"
                        ["amenity"]=>
                        string(6) "school"
                        ["gnis:feature_id"]=>
                        string(6) "602607"
                        ["gnis:state_id"]=>
                        string(2) "25"
                        ["ele"]=>
                        string(2) "34"
                        ["website"]=>
                        string(7) "xyz.org"
                      }
                    }
                    [1]=>
                    array(9) {
                      ["id"]=>
                      string(9) "358264143"
                      ["version"]=>
                      string(1) "1"
                      ["timestamp"]=>
                      string(20) "2009-03-10T04:54:34Z"
                      ["uid"]=>
                      string(4) "4732"
                      ["user"]=>
                      string(7) "iandees"
                      ["changeset"]=>
                      string(6) "774950"
                      ["lat"]=>
                      string(10) "42.2017681"
                      ["lon"]=>
                      string(11) "-70.7561527"
                      ["school"]=>
                      array(8) {
                        ["gnis:created"]=>
                        string(10) "08/27/2002"
                        ["gnis:county_id"]=>
                        string(3) "023"
                        ["name"]=>
                        string(30) "Scituate Center Central School"
                        ["amenity"]=>
                        string(6) "school"
                        ["gnis:feature_id"]=>
                        string(6) "602607"
                        ["gnis:state_id"]=>
                        string(2) "25"
                        ["ele"]=>
                        string(2) "34"
                        ["website"]=>
                        string(7) "xyz.org"
                      }
                    }
                    [2]=>
                    array(9) {
                      ["id"]=>
                      string(9) "358264143"
                      ["version"]=>
                      string(1) "1"
                      ["timestamp"]=>
                      string(20) "2009-03-10T04:54:34Z"
                      ["uid"]=>
                      string(4) "4732"
                      ["user"]=>
                      string(7) "iandees"
                      ["changeset"]=>
                      string(6) "774950"
                      ["lat"]=>
                      string(10) "42.2017681"
                      ["lon"]=>
                      string(11) "-70.7561527"
                      ["school"]=>
                      array(8) {
                        ["gnis:created"]=>
                        string(10) "08/27/2002"
                        ["gnis:county_id"]=>
                        string(3) "023"
                        ["name"]=>
                        string(31) "Walnut Hill School for the Arts"
                        ["amenity"]=>
                        string(6) "school"
                        ["gnis:feature_id"]=>
                        string(6) "602607"
                        ["gnis:state_id"]=>
                        string(2) "25"
                        ["ele"]=>
                        string(2) "34"
                        ["website"]=>
                        string(7) "xyz.org"
                      }
                    }
                  }
                  [URL="https://gitter.im/php-de/chat?utm_source=share-link&utm_medium=link&utm_campaign=share-link"]PHP.de Gitter.im Chat[/URL] - [URL="https://raindrop.io/user/32178"]Meine öffentlichen Bookmarks[/URL] ← Ich habe dir geholfen ? [B][URL="https://www.amazon.de/gp/wishlist/348FHGUZWTNL0"]Beschenk mich[/URL][/B].

                  Kommentar


                  • #10
                    Hallo tr0y guten Morgen

                    du bist ja sowas von Schnell - vielen Dank! Wow


                    PHP-Code:
                    // filter out all child nodes that are not instances of DOMElement-Class
                        
                    $filtered array_filter(iterator_to_array($element->childNodes), function($inbound) {
                        return 
                    $inbound instanceof DOMElement

                    ...werde das heute abend mal alles genauer ansehen - bin grad unterwegs. Das sieht schon super aus: v.a. die Idee mit dem "filter out all child nodes that are not instances of DOMElement-Class"

                    Das denke ich, ist echt super. Und holt im Grunde alle Elemente ein die drinnestecken..



                    Wenn du willst kann ich dir auch ein simplexml-Äquivalent posten.
                    Das wär ja super.


                    2179 School(s) found: the last ones are shown below.....

                    #2151: ID:2688357765 [51.4668941,-0.9731135] New Directrions, North Reading
                    #2152: ID:2702504696 [51.5884265,-0.7829013] Burford School
                    #2153: ID:2702549737 [51.5802201,-0.7653918] Great Marlow School
                    #2154: ID:2706219304 [51.3779317,-0.0895302] ARK Oval Primary Academy
                    #2155: ID:2706219314 [51.3871935,-0.0623001] Ashburton Primary School
                    #2156: ID:2706219320 [51.3210977,-0.1398859] CALAT Smitham Centre
                    #2157: ID:2706219326 [51.3638861,-0.0922032] Elmhurst School
                    #2158: ID:2706219339 [51.4007121,-0.0743710] Harris Academy South Norwood
                    #2159: ID:2706219343 [51.3831662,-0.0405476] Orchard Way Primary School
                    #2160: ID:2706219347 [51.3531047,-0.0959447] Purley Oaks Primary School
                    #2161: ID:2706219348 [51.3428384,-0.0069931] Rowdown Primary School
                    #2162: ID:2706219350 [51.3954917,-0.0732185] South Norwood Primary School
                    #2163: ID:2706219351 [51.3377151,-0.1230482] St David's Preparatory School
                    #2164: ID:2706219353 [51.3993760,-0.1144352] Winterbourne School
                    #2165: ID:2717394621 [51.8706538,0.1480886] Prep
                    #2166: ID:2717394636 [51.8685838,0.1463720] Pre-Prep
                    #2167: ID:2722704201 [51.1398429,-0.0457445] Felbridge Primary School
                    Wäre das ausgabeformat so machbar? Mit einem simplexml-Äquivalent?
                    Wenn ich das so hätte - in dem o.g. Format - wärs klasse.

                    Am Ende will ich das einer Datenbank übergeben - mysql / mongo oder postgresql. Aber das kommt mal später.

                    Freu mich, von dir wieder zu hoeren.


                    LG dilbert

                    Kommentar


                    • #11
                      Sicher geht das:

                      PHP-Code:
                      <?php

                      $xml 
                      = <<<XML
                      <?xml version="1.0" encoding="utf-8"?>
                      <osm version="0.6" generator="osm-extract.pl">
                             <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                             uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                                lon="-70.7561527">
                                 <tag k="gnis:created" v="08/27/2002"/>
                                <tag k="gnis:county_id" v="023"/>
                                <tag k="name" v="Wayland Middle School"/>
                                <tag k="amenity" v="school"/>
                                 <tag k="gnis:feature_id" v="602607"/>
                                 <tag k="gnis:state_id" v="25"/>
                                 <tag k="ele" v="34"/>
                            <tag k="website" v="xyz.org"/>
                       
                       </node>

                             <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                                uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                                 lon="-70.7561527">
                                 <tag k="gnis:created" v="08/27/2002"/>
                                 <tag k="gnis:county_id" v="023"/>
                                 <tag k="name" v="Scituate Center Central School"/>
                                 <tag k="amenity" v="school"/>
                                 <tag k="gnis:feature_id" v="602607"/>
                                 <tag k="gnis:state_id" v="25"/>
                                 <tag k="ele" v="34"/>
                               <tag k="website" v="xyz.org"/>
                       
                             </node>
                             <node id="358264143" version="1" timestamp="2009-03-10T04:54:34Z"
                                 uid="4732" user="iandees" changeset="774950" lat="42.2017681"
                                 lon="-70.7561527">
                                 <tag k="gnis:created" v="08/27/2002"/>
                                 <tag k="gnis:county_id" v="023"/>
                                 <tag k="name" v="Walnut Hill School for the Arts"/>
                                 <tag k="amenity" v="school"/>
                                 <tag k="gnis:feature_id" v="602607"/>
                                 <tag k="gnis:state_id" v="25"/>
                                 <tag k="ele" v="34"/>
                                 <tag k="website" v="xyz.org"/>
                       
                       </node>
                       </osm>
                      XML;

                      $dom simplexml_load_string($xml);

                      // select node-tags where subnode tags property k is amenity and subnode tags property v is school

                      $result $dom->xpath("node[tag/@k='amenity' and tag/@v='school']");

                      // parse result, execute a closure on every found element
                      $data array_map(function(SimpleXMLElement $element) {
                          
                      // parse child nodes, execute a closure on every element that matches our previous filter
                          
                      $mapping array_map(function(SimpleXMLElement $child) {

                              
                      // create a array entry with k-attribute as key and v-attribute as value and return it.
                              
                      $data = array(
                                  (string) 
                      $child->attributes()->=> (string) $child->attributes()->v
                              
                      );

                              return 
                      $data;
                          }, 
                      $element->xpath('./tag'));

                          
                      // convert attributes to an array
                          
                      $attributes $element->attributes();
                          
                      $attributes array_map('strval'iterator_to_array($attributes));

                          
                      // merge all sub arrays to one array level and attach it as tag-entry to the attributes
                          
                      $attributes['school'] = call_user_func_array('array_merge'$mapping);

                          return 
                      $attributes;
                      }, 
                      $result);

                      echo 
                      count($data).' School'.(count($data) === ?: 's').' found: the last ones are shown below.....'.PHP_EOL.PHP_EOL;

                      $linePattern '#{uid}: ID:{id} [{latitude},{longitude}] {name}';

                      $lines = array();
                      foreach ( 
                      $data as $current ) {
                          
                      $lines[] = strtr(
                              
                      $linePattern,
                              array(
                                  
                      '{uid}' => $current['uid'],
                                  
                      '{id}' => $current['id'],
                                  
                      '{latitude}' => $current['lat'],
                                  
                      '{longitude}' => $current['lon'],
                                  
                      '{name}' => $current['school']['name'],
                              )
                          );
                      }

                      echo 
                      join(PHP_EOL$lines);
                      Code:
                      3 Schools found: the last ones are shown below.....
                      
                      #4732: ID:358264143 [42.2017681,-70.7561527] Wayland Middle School
                      #4732: ID:358264143 [42.2017681,-70.7561527] Scituate Center Central School
                      #4732: ID:358264143 [42.2017681,-70.7561527] Walnut Hill School for the Arts
                      [URL="https://gitter.im/php-de/chat?utm_source=share-link&utm_medium=link&utm_campaign=share-link"]PHP.de Gitter.im Chat[/URL] - [URL="https://raindrop.io/user/32178"]Meine öffentlichen Bookmarks[/URL] ← Ich habe dir geholfen ? [B][URL="https://www.amazon.de/gp/wishlist/348FHGUZWTNL0"]Beschenk mich[/URL][/B].

                      Kommentar


                      • #12
                        hallo - vielen herzlichen Dank!!!

                        LG Dilbert


                        Verstaendnisfrage:

                        mit dem Folgenden kann man die Requests -(nach den diversen tags) erweitern....

                        PHP-Code:
                        $linePattern '#{uid}: ID:{id} [{latitude},{longitude}] {name}';

                        $lines = array();
                        foreach ( 
                        $data as $current ) {
                            
                        $lines[] = strtr(
                                
                        $linePattern,
                                array(
                                    
                        '{uid}' => $current['uid'],
                                    
                        '{id}' => $current['id'],
                                    
                        '{latitude}' => $current['lat'],
                                    
                        '{longitude}' => $current['lon'],
                                    
                        '{name}' => $current['school']['name'], 


                        m.a.w.

                        ich koennte hier in dieser Zeile noch mehr Tags angeben - und diese dann ggf. auch finden lassen...!?

                        PHP-Code:
                        $linePattern '#{uid}: ID:{id} [{latitude},{longitude}] {name}'
                        Hab ich das richtig verstanden...!?
                        Das wär super.

                        lg dilbert

                        Kommentar


                        • #13
                          Nein, das Pattern ist nur dafür da um einen String nach einem bestimmten Muster zusammenzubauen. Tags werden automatisch alle abgeholt. Wenn du mehr Werte aus dem Array holen und in dem String platzieren willst, musst du das strtr übergebene Array erweitern und den $linePattern-Pattern anpassen.

                          Die von dir gequoteten Codeabschnitte dienen explizit nur der Darstellung und haben mit dem Besorgen der Daten nichts zu tun.
                          [URL="https://gitter.im/php-de/chat?utm_source=share-link&utm_medium=link&utm_campaign=share-link"]PHP.de Gitter.im Chat[/URL] - [URL="https://raindrop.io/user/32178"]Meine öffentlichen Bookmarks[/URL] ← Ich habe dir geholfen ? [B][URL="https://www.amazon.de/gp/wishlist/348FHGUZWTNL0"]Beschenk mich[/URL][/B].

                          Kommentar


                          • #14
                            hallo trOy

                            danke !!

                            Zitat von tr0y Beitrag anzeigen
                            Tags werden automatisch alle abgeholt. Wenn du mehr Werte aus dem Array holen und in dem String platzieren willst, musst du das strtr übergebene Array erweitern und den $linePattern-Pattern anpassen.
                            Das Besorgen scheint die magische oder m.a.W. entscheidente stelle zu sein. Da werd ich mal nachsehen. Dies würd ich sehr gern noch besser verstehen.
                            Würde gern per default alles (!) holen was drinne ist. Auch wenn die es dann auch mal keine values gibt. Geht das denn!?

                            Werd mir das später mal ansehen. Bin grad sehr auf dem Sprung.

                            Bis später

                            vg dilbert

                            Kommentar


                            • #15
                              Das ist schon der Fall. die Sub-Arrays in $data tragen alle Attribute vom node tag und alle assoziativen Daten aus den Tag-Unterknoten.
                              [URL="https://gitter.im/php-de/chat?utm_source=share-link&utm_medium=link&utm_campaign=share-link"]PHP.de Gitter.im Chat[/URL] - [URL="https://raindrop.io/user/32178"]Meine öffentlichen Bookmarks[/URL] ← Ich habe dir geholfen ? [B][URL="https://www.amazon.de/gp/wishlist/348FHGUZWTNL0"]Beschenk mich[/URL][/B].

                              Kommentar

                              Lädt...
                              X