Demonstrating SimpleXML in PHP5 by utilizing it to grab an XML weather feed from the National Weather Service and display the data, marked up via CSS, on a live site.
8. Access Single Item in Array Ex.4 XML data echo “<h3>” . $xml->item[0]->title . “</h3>”; will return the title for the first item in the array, item 0, which is: City Offers Activities to Celebrate National Historic Preservation Month A single item in the array can be accessed by referring to its position. The following code
17. Local Weather Data Code 01: // Get Weather Routine // 02: $filename = $_SERVER['DOCUMENT_ROOT'] . '/feeds/KARR.xml'; 03: $weatherurl = 'http://www.nws.noaa.gov/data/current_obs/KARR.xml'; 04: $weatherdata = ‘’; 05: // check to see if the local file exists 06: if (file_exists($filename)) { 07: // get difference in seconds between now and last modified date 08: $diff = (time() - filemtime("$filename"))/60*60; 09: // if greater than 1 hr (3600 seconds) get new file from source 10: if ($diff >= 3600) { 11: // check to make sure file has write permissions 12: if (is_writable($filename)) { 13: $weatherdata = file_get_contents($weatherurl); 14: file_put_contents($filename,$weatherdata, LOCK_EX); 15: } 16: }; 17: } else { 18: // file doesn't exist, get data and create new file 19: $weatherdata = file_get_contents($weatherurl); 20: file_put_contents($filename,$weatherdata); 21: } 22: //check again to be sure file exists 23: if (file_exists($filename)) { 24: // write it out 25: $xml = simplexml_load_file($filename); 26: // Insert display code here 27: }
18.
19.
20. Questions? Ron Pringle Web Developer City of Aurora, IL www.aurora-il.org [email_address] Director, Lakes Region National Association of Government Webmasters www.nagw.org [email_address]