Search code examples
phpxmlrsssimplexml

PHP: Count amount of times specific value shows in RSS feed


I am working with the Met Office RSS feed:

$metourl = "http://www.metoffice.gov.uk/public/data/PWSCache/WarningsRSS/Region/UK";
$metoxml = simplexml_load_file($metourl);
$count = $metoxml->channel->item;

I can easily establish if there are any "weather warnings" (in this case):

if($count && $count->count() >= 1){

What I want to do, if possible, is to count how many times 'YELLOW', or 'RED' warnings occur under

$metoxml->channel->item->warningLevel

so I can then echo that?

E.g. "There are x yellow and x red warnings.".

Thank you!


Solution

  • You can use the xpath method:

    $metourl = "http://www.metoffice.gov.uk/public/data/PWSCache/WarningsRSS/Region/UK";
    $metoxml = simplexml_load_file($metourl);
    $metoxml->registerXpathNamespace('metadata',
      'http://metoffice.gov.uk/nswws/module/metadata/1.0');
    $wl = $metoxml->xpath('//channel/item/metadata:warningLevel');
    
    $counters = [ 'YELLOW' => 0, 'RED' => 0 ];
    
    foreach ($wl as $e) {
      $str = trim((string)$e);
      if ($str === 'YELLOW')
        $counters['YELLOW']++;
      elseif ($str === 'RED')
        $counters['RED']++;
    }
    
    printf('There are %d yellow and %d red warnings.',
      $counters['YELLOW'], $counters['RED']);
    

    Sample Output

    There are 14 yellow and 0 red warnings.