开发者

how to parse xml with php

I am trying to read a weather feed from Yahoo to my site. Using the code below I was able to print the xml. What I really want to achieve now is to put the temperature and image in two different variables

 $zipCode = "44418";
 $url = "http://weather.yahooapis.com/forecastrss";
 $zip = "?w=$zipCode";
 $fullUrl = $url . $zip.'&u=c';
 $curlObject = curl_init();
 curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
 curl_setopt($curlObject,CURLOPT_HEADER,false);
 curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
开发者_开发技巧 $returnYahooWeather = curl_exec($curlObject);
 curl_close($curlObject);
 print "yahooWeather". $returnYahooWeather;

//$temperature 
//$image


You should go ahead and use simplexml or DOM to parse the XML and then you can iterate over the results. With SimpleXML this looks like this:

$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
//print "here". $returnYahooWeather;

$xmlobj=simplexml_load_string($returnYahooWeather);

$res = $xmlobj->xpath("//yweather:condition");
$tmp = false;
while(list( , $node) = each($res)) {
  $tmp = $node;
 }
$attribs = $tmp->attributes();
print "Temperature [".$attribs['temp']."]";


I find it easiest to SimpleXML with PHP.

$xml = simplexml_load_string($returnYahooWeather);
echo $xml->Path->To->Temperature;

It's easy enough, and you can use XPath with SimpleXML :). There are other ways of parsing XML too, as previously mentioned DOMDocument is one of them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜