{"id":2649,"date":"2011-01-15T19:17:36","date_gmt":"2011-01-16T00:17:36","guid":{"rendered":"http:\/\/teamtutorials.com\/?p=2649"},"modified":"2012-03-28T08:46:56","modified_gmt":"2012-03-28T12:46:56","slug":"parsing-xml-feed-to-an-array-with-xpath","status":"publish","type":"post","link":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath","title":{"rendered":"Parsing XML Feed to an Array with XPath"},"content":{"rendered":"
Recently while working on a project, I found myself needed to parse several different types of files through the same mechanism (CSV, pipe delimited, XML, and more). I decided that it would be best to get each time of feed to a identical object that could then be run through the same methods regardless of the input type. This tutorial will walk you through using PHP and XPath to parse the values from an XML file and store them into array for later manipulation. <\/p>\n
To start, for those that are unfamiliar with XPath. It is a mechanism which will allow you to easily navigate and retrieve elements and attributes from XML and HTML. It’s preety simple to understand and can make life a lot easier when dealing with these languages.
\nLet’s take a look at the following XML example. An XPath is literally just a path to whatever attribute or element you are looking to get. <\/p>\n
\r\n<?xml version="1.0"?>\r\n<catalog>\r\n <book id="bk101">\r\n <author>Gambardella, Matthew<\/author>\r\n <title>XML Developer's Guide<\/title>\r\n <genre>Computer<\/genre>\r\n <price>44.95<\/price>\r\n <publish_date>2000-10-01<\/publish_date>\r\n <description>An in-depth look at creating applications \r\n with XML.<\/description>\r\n <\/book>\r\n <book id="bk102">\r\n <author>Ralls, Kim<\/author>\r\n <title>Midnight Rain<\/title>\r\n <genre>Fantasy<\/genre>\r\n <price>5.95<\/price>\r\n <publish_date>2000-12-16<\/publish_date>\r\n <description>A former architect battles corporate zombies, \r\n an evil sorceress, and her own childhood to become queen \r\n of the world.<\/description>\r\n <\/book>\r\n<\/catalog>\r\n<\/pre>\n\/\/catalog\/book\/title would return the nodes that match that. In this case, there would be 2.<\/p>\n