Search

7/03/2009

php DOMDocument::loadXML & xpath


class helloAction extends sfAction
{
// data values
// $newsitems -> [ [link, title, desc]* ]
public function execute()
{
$rssurl = 'http://rss.news.yahoo.com/rss/tech';
$rssdata = $this->url_get_contents($rssurl);
$rssdom = DOMDocument::loadXML($rssdata);

// fetch values from dom and put into array of [link,title,desc] arrays
$newsitems = array();
$xpath = new DOMXPath($rssdom);
foreach ($xpath->query("//rss/channel/item") as $item)
{
$link = $this->get_element_value($item, 'link');
$title = $this->get_element_value($item, 'title');
$description = $this->get_element_value($item, 'description');
$newsitems[] = array($link, $title, $description);
}

// pass this struct to the template
$this->newsitems = $newsitems;
}

// note: no error handling yet
private function url_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
private function get_element_value($node, $itemname)
{
return $node->getElementsByTagName($itemname)->item(0)->nodeValue;
}
}

沒有留言: