2016-11-19 74 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.