jQuery + PHP to parse XML

Sharing is Caring

jQuery is very well suited for cross browser JavaScript development, but I bet you didn’t know jQuery is also fairly well suited to parsing XML. I often use jQuery to send XMLHttpRequests and then parse the XML returned by a PHP script on the server and then manipulate the return in some way. I won’t really cover exactly what to do with it because this is so dependent on the purpose of your data.

Parsing the XML isn’t overly difficult with jQuery and will allow you to truly use the power of AJAX and eliminate a lot of the complexity with JavaScript. Of course, getElementByTagName and getAttribute aren’t exactly 100% cross browser compatible, and jQuery is pretty much 100% of the time.

Things to Remember

  • PHP must set the content-type to be specified as text/xml or application/xml as seen in the following code example.
  • If you are using .ajax() you must ensure that the dataType is “xml” or you won’t be able to parse the data returned.


<?php
header ("Content-Type: text/xml");
?>

<your_xml_content>
<site ID="1" >
<Title>BRCline Consulting</Title>
<url>www.brcline.com</url>
</site>
</your_xml_content>

<script type="text/javascript" >
$(document).ready(function(){
$.ajax({
type: "GET",
url: "yourURLHere.php",
dataType: "xml",
success: function(xml) {

}
});
});
</script>

Further Reading
jQuery often has a ton of plugins that can increase the flexibility and decrease the amount of time you spend on writing your own “utility” code. One such plugin available to reduce the amount of time spent on writing utility code for parsing XML/RSS feeds is jFeed.

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring

Comments are closed.