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.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.

Comments are closed.