SimpleXML In PHP 5


Published on

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.

Published in: Technology, Design
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

SimpleXML In PHP 5

  1. 1. SimpleXML Presented by Ron Pringle Webmaster City of Aurora, Illinois
  2. 2. What is XML? <ul><li>XML stands for EXtensible Markup Language </li></ul><ul><li>XML is a markup language much like HTML </li></ul><ul><li>XML was designed to carry data, not to display data </li></ul><ul><li>XML tags are not predefined. You must define your own tags </li></ul><ul><li>XML is designed to be self-descriptive </li></ul><ul><li>XML is a W3C Recommendation </li></ul>Ex.1 Sample XML data
  3. 3. What is SimpleXML? <ul><li>SimpleXML is a PHP extension that converts an XML document into an object that can then be processed with normal property selectors and array iterators. </li></ul><ul><li>SimpleXML functions are part of the PHP core. No installation required. </li></ul><ul><li>SimpleXML requires PHP5+ and is enabled by default. </li></ul>
  4. 4. Example 1: Loading an RSS Feed <ul><li>Our sample XML file structure can be seen in ex.2 </li></ul><ul><li>Create new simpleXML object by loading the file with simplexml_load_file function. </li></ul>Ex.2 Sample RSS feed in XML format $xml = simplexml_load_file(‘sample.xml’);
  5. 5. RSS Feed Code <ul><li>01: <?php </li></ul><ul><li>02: // Create new simpleXML object </li></ul><ul><li>03: $xml = simplexml_load_file(‘sample.xml’); </li></ul><ul><li>04: //Access the title element </li></ul><ul><li>05: echo “<h2>” . $xml->channel->title . “</h2> ”; </li></ul><ul><li>06: //Access all titles, descriptions, links in array </li></ul><ul><li>07: foreach($xml->item as $item) { </li></ul><ul><li>08: echo “<h3>” . $item->title . “</h3> ”; </li></ul><ul><li>09: echo “<p> . $item->description . “</p> ”; </li></ul><ul><li>10: echo “<p><a href=”” . $item->link . “”>More Info</a></p> ”; </li></ul><ul><li>11: } //end foreach xml item </li></ul><ul><li>12: ?> </li></ul>
  6. 6. RSS Feed Display Ex.3 Output from code in example 1
  7. 7. RSS Feed Display <ul><li>Channel title </li></ul>Ex.4 Output from code in example 1 with explanations Item title Item description Item link
  8. 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
  9. 9. Example 2: NWS Weather Feed <ul><li>National Weather Service has XML feeds for about 1,800 locations across the U.S. and U.S. Territories. </li></ul><ul><li>Why use this when there are all those free weather widgets out there? </li></ul><ul><li>This method allows us to control the data, what we want to display, the look and feel of the display, and eliminates commercial advertising from our site. </li></ul>
  10. 10. NWS Weather Feed <ul><li>Locate URL for feed. Aurora Municipal Airport (KARR) current_obs/KARR.xml </li></ul><ul><li>View raw XML to figure out what data is there and what the namespaces are </li></ul><ul><li>Load remote XML file </li></ul><ul><li>Parse the data we’re interested in displaying </li></ul>
  11. 11. Raw XML <ul><li><current_observation version=&quot;1.0&quot; xsi:noNamespaceSchemaLocation=&quot;;> </li></ul><ul><li><credit>NOAA's National Weather Service</credit> </li></ul><ul><li><credit_URL></credit_URL> </li></ul><ul><li><image> </li></ul><ul><li><url></url> </li></ul><ul><li><title>NOAA's National Weather Service</title> </li></ul><ul><li><link></link> </li></ul><ul><li></image> </li></ul><ul><li><suggested_pickup>15 minutes after the hour</suggested_pickup> </li></ul><ul><li><suggested_pickup_period>60</suggested_pickup_period> </li></ul><ul><li><location>Aurora Municipal Airport, IL</location> </li></ul><ul><li><station_id>KARR</station_id> </li></ul><ul><li><latitude>41.77</latitude> </li></ul><ul><li><longitude>-88.47</longitude> </li></ul><ul><li><observation_time>Last Updated on Jun 3, 1:52 pm CDT</observation_time> </li></ul><ul><li><observation_time_rfc822>Tue, 3 Jun 2008 13:52:00 -0500 CDT</observation_time_rfc822> </li></ul><ul><li><weather>Fog/Mist</weather> </li></ul><ul><li><temperature_string>67 F (19 C)</temperature_string> </li></ul><ul><li><temp_f>67</temp_f> </li></ul><ul><li><temp_c>19</temp_c> </li></ul><ul><li><relative_humidity>93</relative_humidity> </li></ul><ul><li><wind_string>From the Southeast at 17 MPH</wind_string> </li></ul><ul><li><wind_dir>Southeast</wind_dir> </li></ul><ul><li><wind_degrees>140</wind_degrees> </li></ul><ul><li><wind_mph>17.25</wind_mph> </li></ul><ul><li><wind_gust_mph>NA</wind_gust_mph> </li></ul><ul><li><pressure_string>29.57&quot; (1001.0 mb)</pressure_string> </li></ul><ul><li><pressure_mb>1001.0</pressure_mb> </li></ul><ul><li><pressure_in>29.57</pressure_in> </li></ul><ul><li><dewpoint_string>65 F (18 C)</dewpoint_string> </li></ul><ul><li><dewpoint_f>65</dewpoint_f> </li></ul><ul><li><dewpoint_c>18</dewpoint_c> </li></ul><ul><li><heat_index_string>NA</heat_index_string> </li></ul><ul><li><heat_index_f>NA</heat_index_f> </li></ul><ul><li><heat_index_c>NA</heat_index_c> </li></ul><ul><li><windchill_string>NA</windchill_string> </li></ul><ul><li><windchill_f>NA</windchill_f> </li></ul><ul><li><windchill_c>NA</windchill_c> </li></ul><ul><li><visibility_mi>5.00</visibility_mi> </li></ul><ul><li><icon_url_base></icon_url_base> </li></ul><ul><li><icon_url_name>fg.jpg</icon_url_name> </li></ul><ul><li><two_day_history_url></two_day_history_url> </li></ul><ul><li><ob_url></ob_url> </li></ul><ul><li><disclaimer_url></disclaimer_url> </li></ul><ul><li><copyright_url></copyright_url> </li></ul><ul><li><privacy_policy_url></privacy_policy_url> </li></ul><ul><li></current_observation> </li></ul>
  12. 12. Weather Code <ul><li>01: $weatherURL = ‘’; </li></ul><ul><li>02: if(file_exists($weatherURL)) { </li></ul><ul><li>03: $xml = simplexml_load_string($weatherURL); </li></ul><ul><li>04: echo ‘<h3 class=“centertxt”>Current Weather</h3>’; </li></ul><ul><li>05: echo ‘<img class=“floatleftclearsmallborder” src=“$xml->icon_url_base . $xml->icon_url_name”/>’; </li></ul><ul><li>06: echo’<h2>’ . $xml->weather . ‘</p>’; </li></ul><ul><li>07: echo ‘<br class=“clear” />’; </li></ul><ul><li>08: echo ‘<ul class=“nobulletlist”>’; </li></ul><ul><li>09: echo '<li><strong>Wind Chill (°F): </strong>' . $xml->windchill_f . '</li>'; </li></ul><ul><li>10: echo '<li><strong>Heat Index (°F): </strong>' . $xml->heat_index_f . '</li>'; </li></ul><ul><li>11: echo '<li><strong>Humidity: </strong>' . $xml->relative_humidity . '%</li>'; </li></ul><ul><li>12: echo '<li><strong>Wind: </strong>' . $xml->wind_string . '</li>'; </li></ul><ul><li>13: echo '<li><strong>Pressure: </strong>' . $xml->pressure_in . '</li>'; </li></ul><ul><li>14: echo '<li><strong>Dewpoint: </strong>' . $xml->dewpoint_f . '</li>'; </li></ul><ul><li>15: echo '</ul>'; </li></ul><ul><li>16: echo '<p class=&quot;centertxt&quot;><em>' . $xml->observation_time . '</em></p>'; </li></ul><ul><li>17: echo '<p class=&quot;centertxt&quot;><a href=&quot; MapClick.php?CityName=Aurora&state=IL&site=LOT&quot;>view forecast</a></p>'; </li></ul><ul><li>18: } else { </li></ul><ul><li>19: echo “<p>Sorry, no weather data available at this time.</p>”; </li></ul><ul><li>20: } </li></ul>
  13. 13. Weather Display
  14. 14. Weather Notes <ul><li>Data and weather image dynamically loaded from NWS site for every single visit </li></ul><ul><li>Eats up bandwidth and NWS server resources </li></ul><ul><li>What if data isn’t available due to server offline, fiber cut, service outage, etc.? </li></ul><ul><li>Takes longer to load from external source, which, in turn, slows down the loading of our page </li></ul>
  15. 15. Accessing Data Locally <ul><li>Problem </li></ul>External data source getting called with each page load, even though data is only updated once an hour. Solution Load data once, write to local file and only update once an hour.
  16. 16. Local Weather Data Outline <ul><li>Copy XML data to local file </li></ul><ul><li>Store weather images locally </li></ul><ul><li>Check for existence of local file </li></ul><ul><li>If it doesn’t exist, we’ll create it </li></ul><ul><li>If it does, compare last modified date </li></ul><ul><li>Depending on date, load local data or refresh file from external source </li></ul>
  17. 17. Local Weather Data Code 01: // Get Weather Routine // 02: $filename = $_SERVER['DOCUMENT_ROOT'] . '/feeds/KARR.xml'; 03: $weatherurl = ''; 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(&quot;$filename&quot;))/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. 18. Local Weather Data Display <ul><li>Visually the same </li></ul><ul><li>Only one call to the external data is made every hour </li></ul><ul><li>No calls to external images are made </li></ul>
  19. 19. Live Sample with Code <ul><li> </li></ul>
  20. 20. Questions? Ron Pringle Web Developer City of Aurora, IL [email_address] Director, Lakes Region National Association of Government Webmasters [email_address]