PHP:计算特定值在 RSS 提要中显示的次数

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

我正在使用英国气象局 RSS 提要:

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

我可以很容易地确定是否有 "weather warnings"(在这种情况下):

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

如果可能的话,我想做的是计算'YELLOW''RED'警告在

下出现的次数
$metoxml->channel->item->warningLevel

所以我可以回应吗?

例如"There are x yellow and x red warnings.".

谢谢!

您可以使用xpath方法:

$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']);

示例输出

There are 14 yellow and 0 red warnings.