0

GoogleマップのRESTAPIによって返されるXMLから<address_component>対応する要素内の値を取得しようとしています。<type>postal_code</type>

たとえば、以下のようになります。

    ...

  <result>    
    <type>
      route
    </type>    
    <formatted_address>
      Rose Ln, Liverpool, Merseyside L18 5ED, UK
    </formatted_address>    
    <address_component>      
      <long_name>
        Rose Ln
      </long_name>      
      <short_name>
        Rose Ln
      </short_name>      
      <type>
        route
      </type>      
    </address_component>    
    <address_component>      
      <long_name>
        Liverpool
      </long_name>      
      <short_name>
        Liverpool
      </short_name>      
      <type>
        locality
      </type>      
      <type>
        political
      </type>      
    </address_component>    
    <address_component>      
     ...      
    </address_component>    
    <address_component>      
    ...
    </address_component>    
    <address_component>      
      <long_name>
        L18 5ED
      </long_name>      
      <short_name>
        L18 5ED
      </short_name>      
      <type>
        postal_code
      </type>      
    </address_component>    
    <address_component>      
    ...      
    </address_component>    
   ...    
  </result>

  ... more result elements

<result>要素の1つが表示されます。<address_component>内部には複数の要素がネストされています。それらの1つの中には<type>postal_code</type>

私の質問は、これらの同じ名前の要素をどのように区別し、それに起因する<address_component>withのみを選択するのかということです。<type>postal_code</type>

それらに一意の名前が付けられている場合は、次のような単純なケースになります。

foreach ($address_rsponse->result as $address_option) {
    $val = $address_option->some_unique_name;      
}

ただし、同じ名前を付けると、子要素によって要素を選択する方法に困惑します。

誰かが正しいアプローチに光を当てることができますか?

ありがとう

4

1 に答える 1

1

SimpleXMLでXPathを使用できます( docs)。

<address_component>以下は、探している要素を含む配列を提供します。

$address_rsponse->result->xpath(
    'address_component[normalize-space(type)="postal_code"]')

要素をループしたい場合は、以下を実行すると、探している要素<result>を含む配列が得られ、それぞれの最初の要素が出力されます。<address_component><result>

foreach ($address_rsponse->result as $result) {
    $postal_codes = $result->xpath('address_component[normalize-space(type)="postal_code"]');
    // Do whatever with the postal code(s)
    echo trim($postal_codes[0]->long_name);
}
于 2012-04-27T17:44:09.277 に答える