{"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

This is the basic idea behind XPath. If you are interested in learning more or need more information please review the information that they have over at w3schools<\/a> on the subject. They will be able to provide everything you need to get started.<\/p>\n

First lets create our method that will do the actually data collection for us:<\/p>\n

\r\n   function parseXML($feed_url,$field_xpaths)\r\n    {\r\n        \/\/Get file from url\r\n        $file_contents = file_get_contents($feed_url);\r\n        \r\n        \/\/create xml object\r\n        $xml = new SimpleXMLElement($file_contents);\r\n\r\n        \/\/Work through all fields we need to collect\r\n        foreach($field_xpaths[0] as $key=>$field_xpath)\r\n        {\r\n            $count = 0;\r\n\r\n            \/\/Get an array of fields that match the current xpath\r\n            $xpath_returns = $xml->xpath($field_xpath);\r\n            \/\/Iterate through the array and assign values to the coupon array\r\n            while(list( , $node) = each($xpath_returns))\r\n            {\r\n                $rows[$count][$key] = $node;\r\n                $count++;\r\n            }\r\n        }\r\n\r\n        return $rows;\r\n    }\r\n<\/pre>\n

When you break this down, you see how simple this really is to achieve. The way this function is written, it will accept an array for the $field_xpaths variable. Then it will iterate the through the array treating each as it’s own xpath. Each value will use it’s key in the array as it’s name (in my example, these values are pulled from a database, so the column name is the name of the key for that value in the array). <\/p>\n

It first grabs the entire contents of the file and associates a SimpleXMLElements object to them. This object will allow us to use XPath operators to navigate through our nodes. For each set in the array (key and value) we get all values that match the XPath provided. We then iterate through each value in the returned array and store it in a master array (in this case it’s just called rows). When this is done processing, all values for each xpath will be stored in an multi dimensional array that you can call by name. For example, I said that mine were from a database and one of my column names (which would then become a key in the array of results) was named store_name. I would then be able to access the stores at $rows[intCount][‘store_name’].<\/p>\n

\r\n$field_locations = getFieldLocations($result['feed_id']); \/\/Method to query the database and get the XPath values from it. \r\n$feed_array = parseXML($result['feed_url'],$field_locations); \/\/Calls the parser method.\r\n<\/pre>\n

The above code just calls the function and store the result into the array. You can now take this array and do what you need to with it. That concludes this tutorial. I hope it was easy to follow, and as always, feel free to comment or ask questions. Thanks for reading. <\/p>\n","protected":false},"excerpt":{"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","protected":false},"author":2,"featured_media":2935,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[24,25,119],"tags":[],"yoast_head":"\nParsing XML Feed to an Array with XPath<\/title>\n<meta name=\"description\" content=\"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.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Mike Maguire\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/teamtutorials.com\/#website\",\"url\":\"https:\/\/teamtutorials.com\/\",\"name\":\"Team Tutorials\",\"description\":\"Learn something new today\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/teamtutorials.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/teamtutorials.com\/wp-content\/uploads\/2011\/01\/xml_5.png\",\"contentUrl\":\"https:\/\/teamtutorials.com\/wp-content\/uploads\/2011\/01\/xml_5.png\",\"width\":\"256\",\"height\":\"256\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#webpage\",\"url\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath\",\"name\":\"Parsing XML Feed to an Array with XPath\",\"isPartOf\":{\"@id\":\"https:\/\/teamtutorials.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#primaryimage\"},\"datePublished\":\"2011-01-16T00:17:36+00:00\",\"dateModified\":\"2012-03-28T12:46:56+00:00\",\"author\":{\"@id\":\"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b\"},\"description\":\"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.\",\"breadcrumb\":{\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/teamtutorials.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Parsing XML Feed to an Array with XPath\"}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b\",\"name\":\"Mike Maguire\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/teamtutorials.com\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r\",\"caption\":\"Mike Maguire\"},\"sameAs\":[\"http:\/\/mikemaguire.me\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Parsing XML Feed to an Array with XPath","description":"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.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath","twitter_misc":{"Written by":"Mike Maguire","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebSite","@id":"https:\/\/teamtutorials.com\/#website","url":"https:\/\/teamtutorials.com\/","name":"Team Tutorials","description":"Learn something new today","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/teamtutorials.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#primaryimage","inLanguage":"en-US","url":"https:\/\/teamtutorials.com\/wp-content\/uploads\/2011\/01\/xml_5.png","contentUrl":"https:\/\/teamtutorials.com\/wp-content\/uploads\/2011\/01\/xml_5.png","width":"256","height":"256"},{"@type":"WebPage","@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#webpage","url":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath","name":"Parsing XML Feed to an Array with XPath","isPartOf":{"@id":"https:\/\/teamtutorials.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#primaryimage"},"datePublished":"2011-01-16T00:17:36+00:00","dateModified":"2012-03-28T12:46:56+00:00","author":{"@id":"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b"},"description":"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.","breadcrumb":{"@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/parsing-xml-feed-to-an-array-with-xpath#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/teamtutorials.com\/"},{"@type":"ListItem","position":2,"name":"Parsing XML Feed to an Array with XPath"}]},{"@type":"Person","@id":"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b","name":"Mike Maguire","image":{"@type":"ImageObject","@id":"https:\/\/teamtutorials.com\/#personlogo","inLanguage":"en-US","url":"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r","caption":"Mike Maguire"},"sameAs":["http:\/\/mikemaguire.me"]}]}},"_links":{"self":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/posts\/2649"}],"collection":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/comments?post=2649"}],"version-history":[{"count":0,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/posts\/2649\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/media\/2935"}],"wp:attachment":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/media?parent=2649"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/categories?post=2649"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/tags?post=2649"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}