The caffeine fuelled writings of a web developer


jQuery XML and PHP web service

Posted on March 29th 2016  //  Filed under: Web Development

I’m a true follower of the Church of PHP. However, as the applications I’m building are becoming more and more complex I need to think about the performance of my applications. Getting the data from third-party services and processing it all in PHP started to become cumbersome and really affected performance.

I decided I could improve this by having the data processing done on the front end. Client side meant that I could depend on the end user’s hardware rather than my server doing all the hard work. Its possible to write a jQuery XML script to process our data on the client-side.

Example XML structure

This is a sample response from an RSS feed. You can see its a fairly standard structure. Media:thumbnail will only appear if an image has been included.

      <title>Libraries 'facing greatest crisis'</title>  
      <description>Almost 8,000 jobs in UK libraries have disappeared in six years, about a quarter of the overall total, an investigation by the BBC reveals.</description>  
      <guid isPermaLink="false"></guid>  
      <pubDate>Tue, 29 Mar 2016 12:17:49 GMT</pubDate>  
      <media:thumbnail width="66" height="49" url=""/>  
      <media:thumbnail width="144" height="81" url=""/> 

PHP web service

We need to set up a simple service to get the XML data. You can either output this to the same file (as below) or write a few extra lines and write it to a local XML file.

 $data = file_get_contents("");
 header('Content-type: application/xml');
 echo $data;

jQuery XML

Instead of processing the data in PHP and create an overhead for our server for each news item, we can use the now local XML data and render its results using our jQuery XML script.

  $.get("service.php", function (data) {
    $(data).find("item").each(function () {
      var el = $(this);
      console.log("title      : " + el.find("title").text());
      console.log("description: " + el.find("description").text());

Summing up

As developers now work with significantly larger data sets, its important that you plan architecture around performance. Using server-side languages as a service that provides a data response but doesn’t process it can result in a massive increase in application performance.

If your application pulls through live data I’d recommend that you set up a cron job or similar for your PHP web service to write to a local file every minute or so. Then simply use your jQuery XML as is and it will pull through the most recent data when a users uses your application.

Get in touch

I hope you’ve found this tutorial useful. Start pulling through the data from your web services and let me know how you present it to the end user! Email me or tweet me as usual!