Saturday, April 6, 2013

Parse XML using jQuery

In this tutorial I'll show you how to parse XML file using jQuery. PHP will generate a XML file and jQuery will parse it and create HTML code for web page. jQuery has a pretty cool function that converts XML file to DOM.

SEO friendly feature in weather.php is to add HTTP header with MIME description before sending file to client. File weather.html is to be loaded in browser and file weather.php should be in the same folder. Both files should be in web root folder of Apache web server or it's subfolder.

Filename:weather.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery and XML file in action</title>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
 $.get('weather.php', function(data) {
  $('#city').empty();
  $(data).find('entry').each(function() {
   var $entry = $(this);
   var html = '<div>';
   html += "weather on ";
   html += $entry.attr('coast');
   html += " coast city named ";
   html += $entry.find('city').text();
   html += " is ";
   html += $entry.find('forecast').text();
   html += '<br /></div>';
   $('#city').append($(html));
  });
 });
});
</script>
<div id="container">
    <h1>jQuery parses XML file with attributes</h1>
  <div id="mainContent">
    <div id="city"></div>
  </div>
</div>
</body>
</html>

Note how we use CDATA in XML file to force browser to preserve non breaking space. In production environment we would use a PHP script that takes data from a weather web service or generates XML file based on MySQL table.

Filename:weather.php

<?php
header ("content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>
<entries>
  <entry coast="east">
    <city>Los<![CDATA[&nbsp;]]>Angeles</city>
 <forecast>Fine</forecast>
  </entry>
    <entry coast="east">
    <city>San<![CDATA[&nbsp;]]>Antonio</city>
 <forecast>Rainy</forecast>
  </entry>
  <entry coast="west">
    <city>Boston</city>
 <forecast>Sunny</forecast>
  </entry>
  <entry coast="west">
    <city>Miami</city>
 <forecast>Clouds</forecast>
  </entry>
</entries>';
?>

The advantages of such approach are that client does formating data and server delivers data. That reduces server load. Disadvantage is that such web page is not quite SEO friendly.

No comments:

Post a Comment