user2720975 user2720975 - 1 year ago 76
PHP Question

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

I am working with the Met Office RSS feed:

$metourl = "";
$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
, or
warnings occur under


so I can then echo that?

"There are x yellow and x red warnings."

Thank you!

Answer Source

You can use the xpath method:

$metourl = "";
$metoxml = simplexml_load_file($metourl);
$wl = $metoxml->xpath('//channel/item/metadata:warningLevel');

$counters = [ 'YELLOW' => 0, 'RED' => 0 ];

foreach ($wl as $e) {
  $str = trim((string)$e);
  if ($str === 'YELLOW')
  elseif ($str === 'RED')

printf('There are %d yellow and %d red warnings.',
  $counters['YELLOW'], $counters['RED']);

Sample Output

There are 14 yellow and 0 red warnings.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download