tags:

views:

21

answers:

2

I only want the first and the second last Area nodes - how would I do that here?

$url = "http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB";
   $results = simplexml_load_file($url);
    foreach($results->Location as $location) {
        echo "<hr />";
        foreach($location->Address as $address) {
            foreach($address->Areas as $areas) {
                foreach($areas->Area as $area) {
                    echo $area;
                    echo "<br />";
                }
            }
        }
   }
A: 

Here it is:

<?php

    $url = 'http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&amp;countryCode=GB';
    $results = simplexml_load_file($url);
    $areas = array();
    foreach ($results->Location->Address->Areas->Area as $area)
    {
        $areas[] = (string) $area;
    }

    $first = $areas[0];

    $second_last = $areas[count($areas)-2];

?>
Otar
$last contains the last element but Ashley asked for "and the _second_ last"
VolkerK
I've modified the code, thanks for note...
Otar
+1  A: 

Update: If you have those foreach-loops anyway you can simply use:

$url = "http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&amp;countryCode=GB";
$results = simplexml_load_file($url);
foreach($results->Location as $location) {
  foreach($location->Address as $address) {
    foreach( $address->Areas as $areas) {
      // <-- todo: add test if those two elements exist -->
      echo $areas->Area[0], ' - ', $areas->Area[count($areas->Area)-1], "\n";
    }
  }
}

You can use XPath for this.

<?php
$doc = new SimpleXMLElement('<foo>
  <bar>a</bar>
  <bar>b</bar>
  <bar>c</bar>
  <bar>x</bar>
  <bar>y</bar>
  <bar>z</bar>
</foo>');

$nodes = $doc->xpath('bar[position()=1 or position()=last()-1]');
foreach( $nodes as $n ) {
  echo $n, "\n";
}

prints

a
y

see also:

VolkerK
Yay thank you so much - works a treat! :)
Ashley