返回URL而不是图像 - 使用PHP正则表达式从XML中提取数据

时间:2011-12-13 19:31:58

标签: php xml regex rss

我有一个名为get_current_weather_data()的函数,它基本上可以从Yahoo XML feed获取天气。我可以返回我喜欢的所有值,例如位置,温度和当前条件;我无法获得与当前条件相关的图像。

这是我试图吸引图像的区域:

// get weather icon url 
$description = $xml->channel->item->description;

//preg match regular expression to extract weather icon
$imgpattern = '/src="(.*?)"/i';
preg_match($imgpattern, $description, $matches);

$weather['icon_url'] = $matches[1];
echo $weather['icon_url'];

上述代码返回的内容只是图片网址,而不是图片。任何的想法?

供稿网址:

http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f

或者如果您愿意,我上面提到的上述网址的片段:(请注意我目前正在进行的img src)

<description>
<![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/34.gif"/><br /> <b>Current Conditions:</b><br     /> Fair, 40 F<BR /> <BR /><b>Forecast:</b><BR /> Tue - Sunny. High: 44 Low: 32<br /> Wed -     Partly Cloudy. High: 47 Low: 39<br /> <br /> <a href="http://us.rd.yahoo.com/dailynews/rss/weather/New_York__NY/*http://weather.yahoo.com/forecast/USNY0996_f.html">Full Forecast at Yahoo! Weather</a><BR/><BR/> (provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>

]]&GT;     

get_current_weather_data()函数:

function get_current_weather_data() {

// Get XML data from source
$feed = file_get_contents("http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f");

// Check to ensure the feed exists
if (!$feed) {
    die('Weather not found! Check feed URL');
}

$xml = new SimpleXmlElement($feed);

$weather['city'] = $xml->channel->children('yweather', TRUE)->location->attributes()->city;
echo $weather['city'] . "<br />";

$weather['temp'] = $xml->channel->item->children('yweather', TRUE)->condition->attributes()->temp;
echo $weather['temp'] . "<br />";

$weather['conditions'] = $xml->channel->item->children('yweather', TRUE)->condition->attributes()->text;
echo $weather['conditions'] . "<br />";

// get weather icon url 
$description = $xml->channel->item->description;

//preg match regular expression to extract weather icon
$imgpattern = '/src="(.*?)"/i';
preg_match($imgpattern, $description, $matches);

$weather['icon_url'] = $matches[1];
echo $weather['icon_url'];

return $weather;
}

1 个答案:

答案 0 :(得分:0)

如果您想获取实际的图像数据,可以使用

file_get_contents($weather['icon_url']);