2016-11-19 91 views
1

我與氣象局RSS提要的工作:PHP:計算時間的特定值金額顯示RSS提要

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

我可以很容易地確定是否有任何「天氣預警」(在這種情況下):

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

我想要做什麼,如果可能的話,是統計

$metoxml->channel->item->warningLevel 
下了多少次 'YELLOW',或 'RED'警告時

那麼我可以回聲呢?

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

謝謝!

回答

0

可以使用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.