note 97608 modified in domdocument.getelementsbytagname by danbrown

From: Date: Wed, 28 Apr 2010 14:54:19 +0000
Subject: note 97608 modified in domdocument.getelementsbytagname by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168762@lists.php.net to get a copy of this message
The following takes a list of news items from an XML file (or an RSS feed), assigning it to an array first for a name value pair and then generating an HTML list. <?php $xml =<<<EOT <?xml version="1.0" encoding="ISO-8859-1"?> <news> <item> <title>News 1</title> <created>04/2/2010 08:00 EST</created> <url>http://news.example.com/news.pdf</url> </item> <item> <title>News 2</title> <created>04/25/2010 08:00 EST</created> <url>http://news.example.com/news.pdf</url> </item> <item> <title>News 3</title> <created>04/27/2010 08:00 EST</created> <url>http://news.example.com/news.pdf</url> </item> </news> EOT; $doc = new DOMDocument(); if ($doc->loadXML($xml)) { $items = $doc->getElementsByTagName('item'); $headlines = array(); foreach($items as $item) { $headline = array(); if($item->childNodes->length) { foreach($item->childNodes as $i) { $headline[$i->nodeName] = $i->nodeValue; } } $headlines[] = $headline; } if(!empty($headlines)) { $hc = 0; echo '<ul>'; foreach($headlines as $headline) { if(++$hc <= 3) { echo '<li>' .'<a href="'.$headline['url'].'" target="_blank">' .'<span>'.date('F j, Y', strtotime($headline['created'])).'</span><br />' .$headline['title'] .'</a>' .'</li>'; } } echo '</ul>'; } } ?> --was-- The following takes a list of news items from an XML file (or an RSS feed), assigning it to an array first for a name value pair and then generating an HTML list. <?php $xml =<<<EOT <?xml version="1.0" encoding="ISO-8859-1"?> <news> <item> <title>News 1</title> <created>04/2/2010 08:00 EST</created> <url>http://news.com/news.pdf</url> </item> <item> <title>News 2</title> <created>04/25/2010 08:00 EST</created> <url>http://news.com/news.pdf</url> </item> <item> <title>News 3</title> <created>04/27/2010 08:00 EST</created> <url>http://news.com/news.pdf</url> </item> </news> EOT; $doc = new DOMDocument(); if ($doc->loadXML($xml)) { $items = $doc->getElementsByTagName('item'); $headlines = array(); foreach($items as $item) { $headline = array(); if($item->childNodes->length) { foreach($item->childNodes as $i) { $headline[$i->nodeName] = $i->nodeValue; } } $headlines[] = $headline; } if(!empty($headlines)) { $hc = 0; echo '<ul>'; foreach($headlines as $headline) { if(++$hc <= 3) { echo '<li>' .'<a href="'.$headline['url'].'" target="_blank">' .'<span>'.date('F j, Y', strtotime($headline['created'])).'</span><br />' .$headline['title'] .'</a>' .'</li>'; } } echo '</ul>'; } } ?> http://php.net/manual/en/domdocument.getelementsbytagname.php

« previous php.notes (#168762) next »