simplexml in php 5

20
SimpleXML Presented by Ron Pringle Webmaster City of Aurora, Illinois

Upload: ron-pringle

Post on 29-Nov-2014

6.461 views

Category:

Technology


1 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: SimpleXML In PHP 5

SimpleXML

Presented by

Ron Pringle

WebmasterCity of Aurora, Illinois

Page 2: SimpleXML In PHP 5

What is XML?

• XML stands for EXtensible Markup Language

• XML is a markup language much like HTML

• XML was designed to carry data, not to display data

• XML tags are not predefined. You must define your own tags

• XML is designed to be self-descriptive

• XML is a W3C Recommendation Ex.1 Sample XML data

Page 3: SimpleXML In PHP 5

What is SimpleXML?• 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.

• SimpleXML functions are part of the PHP core. No installation required.

• SimpleXML requires PHP5+ and is enabled by default.

Page 4: SimpleXML In PHP 5

Example 1: Loading an RSS Feed

1. Our sample XML file structure can be seen in ex.2

2. Create new simpleXML object by loading the file with simplexml_load_file function.

Ex.2 Sample RSS feed in XML format

$xml = simplexml_load_file(‘sample.xml’);

Page 5: SimpleXML In PHP 5

RSS Feed Code01:<?php

02: // Create new simpleXML object

03: $xml = simplexml_load_file(‘sample.xml’);

04: //Access the title element

05: echo “<h2>” . $xml->channel->title . “</h2>\n”;

06: //Access all titles, descriptions, links in array

07: foreach($xml->item as $item) {

08: echo “<h3>” . $item->title . “</h3>\n”;

09: echo “<p> . $item->description . “</p>\n”;

10: echo “<p><a href=\”” . $item->link . “\”>More Info</a></p>\n”;

11: } //end foreach xml item

12:?>

Page 6: SimpleXML In PHP 5

RSS Feed Display

Ex.3 Output from code in example 1

Page 7: SimpleXML In PHP 5

RSS Feed Display

Channel title

Ex.4 Output from code in example 1 with explanations

Item title

Item description

Item link

Page 8: SimpleXML In PHP 5

Access Single Item in Array

Ex.4 XML data

echo “<h3>” . $xml->item[0]->title . “</h3>\n”;

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

Page 9: SimpleXML In PHP 5

Example 2: NWS Weather Feed

• National Weather Service has XML feeds for about 1,800 locations across the U.S. and U.S. Territories.

• Why use this when there are all those free weather widgets out there?

• 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.

Page 10: SimpleXML In PHP 5

NWS Weather Feed1. Locate URL for feed. Aurora

Municipal Airport (KARR) http://www.weather.gov/data/current_obs/KARR.xml

2. View raw XML to figure out what data is there and what the namespaces are

3. Load remote XML file

4. Parse the data we’re interested in displaying

Page 11: SimpleXML In PHP 5

Raw XML<current_observation version="1.0"

xsi:noNamespaceSchemaLocation="http://www.weather.gov/data/current_obs/current_observation.xsd">

<credit>NOAA's National Weather Service</credit> <credit_URL>http://weather.gov/</credit_URL> <image> <url>http://weather.gov/images/xml_logo.gif</url>

<title>NOAA's National Weather Service</title><link>http://weather.gov</link>

</image><suggested_pickup>15 minutes after the

hour</suggested_pickup><suggested_pickup_period>60</suggested_pickup_period><location>Aurora Municipal Airport, IL</location><station_id>KARR</station_id><latitude>41.77</latitude><longitude>-88.47</longitude><observation_time>Last Updated on Jun 3, 1:52 pm

CDT</observation_time><observation_time_rfc822>Tue, 3 Jun 2008 13:52:00 -0500

CDT</observation_time_rfc822><weather>Fog/Mist</weather><temperature_string>67 F (19 C)</temperature_string><temp_f>67</temp_f><temp_c>19</temp_c><relative_humidity>93</relative_humidity><wind_string>From the Southeast at 17 MPH</wind_string><wind_dir>Southeast</wind_dir>

<wind_degrees>140</wind_degrees><wind_mph>17.25</wind_mph><wind_gust_mph>NA</wind_gust_mph><pressure_string>29.57" (1001.0 mb)</pressure_string><pressure_mb>1001.0</pressure_mb><pressure_in>29.57</pressure_in><dewpoint_string>65 F (18 C)</dewpoint_string><dewpoint_f>65</dewpoint_f><dewpoint_c>18</dewpoint_c><heat_index_string>NA</heat_index_string><heat_index_f>NA</heat_index_f><heat_index_c>NA</heat_index_c><windchill_string>NA</windchill_string><windchill_f>NA</windchill_f><windchill_c>NA</windchill_c><visibility_mi>5.00</visibility_mi><icon_url_base>http://weather.gov/weather/images/fcicons/</

icon_url_base><icon_url_name>fg.jpg</icon_url_name><two_day_history_url>http://www.weather.gov/data/

obhistory/KARR.html</two_day_history_url><ob_url>http://www.nws.noaa.gov/data/METAR/KARR.1.txt</

ob_url><disclaimer_url>http://weather.gov/disclaimer.html</

disclaimer_url><copyright_url>http://weather.gov/disclaimer.html</

copyright_url><privacy_policy_url>http://weather.gov/notice.html</

privacy_policy_url></current_observation>

Page 12: SimpleXML In PHP 5

Weather Code01: $weatherURL = ‘http://www.nws.noaa.gov/data/current_obs/KARR.xml’;02: if(file_exists($weatherURL)) {03: $xml = simplexml_load_string($weatherURL);04: echo ‘<h3 class=“centertxt”>Current Weather</h3>’;05: echo ‘<img class=“floatleftclearsmallborder” src=“$xml->icon_url_base . $xml-

>icon_url_name”/>’;06: echo’<h2>’ . $xml->weather . ‘</p>’;07: echo ‘<br class=“clear” />’;08: echo ‘<ul class=“nobulletlist”>’;09: echo '<li><strong>Wind Chill (&#176;F): </strong>' . $xml->windchill_f . '</li>';10: echo '<li><strong>Heat Index (&#176;F): </strong>' . $xml->heat_index_f .

'</li>';11: echo '<li><strong>Humidity: </strong>' . $xml->relative_humidity . '%</li>';12: echo '<li><strong>Wind: </strong>' . $xml->wind_string . '</li>';13: echo '<li><strong>Pressure: </strong>' . $xml->pressure_in . '</li>';14: echo '<li><strong>Dewpoint: </strong>' . $xml->dewpoint_f . '</li>';15: echo '</ul>';16: echo '<p class="centertxt"><em>' . $xml->observation_time . '</em></p>';17: echo '<p class="centertxt"><a href="http://www.crh.noaa.gov/forecast/

MapClick.php?CityName=Aurora&state=IL&site=LOT">view forecast</a></p>';18: } else {19: echo “<p>Sorry, no weather data available at this time.</p>”;20: }

Page 13: SimpleXML In PHP 5

Weather Display

Page 14: SimpleXML In PHP 5

Weather Notes

• Data and weather image dynamically loaded from NWS site for every single visit

• Eats up bandwidth and NWS server resources

• What if data isn’t available due to server offline, fiber cut, service outage, etc.?

• Takes longer to load from external source, which, in turn, slows down the loading of our page

Page 15: SimpleXML In PHP 5

Accessing Data Locally

Problem

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.

Page 16: SimpleXML In PHP 5

Local Weather Data Outline

1. Copy XML data to local file

2. Store weather images locally

3. Check for existence of local file

4. If it doesn’t exist, we’ll create it

5. If it does, compare last modified date

6. Depending on date, load local data or refresh file from external source

Page 17: SimpleXML In PHP 5

Local Weather Data Code01: // 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 exists06: if (file_exists($filename)) {07: // get difference in seconds between now and last modified date08: $diff = (time() - filemtime("$filename"))/60*60;09: // if greater than 1 hr (3600 seconds) get new file from source10: if ($diff >= 3600) {11: // check to make sure file has write permissions12: 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 file19: $weatherdata = file_get_contents($weatherurl);20: file_put_contents($filename,$weatherdata);21: }22: //check again to be sure file exists23: if (file_exists($filename)) {24: // write it out25: $xml = simplexml_load_file($filename);26: // Insert display code here 27: }

Page 18: SimpleXML In PHP 5

Local Weather Data Display

• Visually the same• Only one call to the

external data is made every hour

• No calls to external images are made

Page 19: SimpleXML In PHP 5

Live Sample with Code

http://www.aurora-il.org/sample/xml_sample.php

Page 20: SimpleXML In PHP 5

Questions?

Ron Pringle

Web Developer

City of Aurora, IL

www.aurora-il.org

[email protected]

Director, Lakes Region

National Association of Government Webmasters

www.nagw.org

[email protected]