Parsing XML

From Nephtali Documentation

Jump to: navigation, search

Nephtali provides the function n\xml\parse() that makes it easy to parse XML and retrieve the data in whatever format you'd like. The function makes use of PHP's SimpleXMLElement class to process the XML, and returns the data in whatever format you'd prefer.

The function works by passing in a container variable (array or object), and an array of XPATH keys and function values. Any XPATH matches are passed into their corresponding function, along with the container variable. You build up the container however you'd like, and then pass back the container.

Example

In the example below, the download feed from Google Code is parsed to retrieve the link and title for each download.

$xml_str = <<<EOD
<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 <updated>2009-12-14T20:43:55Z</updated>
 <id>http://code.google.com/feeds/p/nephtali/downloads/basic</id>
 <title>Downloads for project nephtali on Google Code</title>
 <link rel="self" type="application/atom+xml;type=feed" href="http://code.google.com/feeds/p/nephtali/downloads/basic"/>
 <link rel="alternate" type="text/html" href="http://code.google.com/p/nephtali/downloads/list"/>
 <entry>
 <updated>2009-12-14T20:43:55Z</updated>
 <id>http://code.google.com/feeds/p/nephtali/downloads/basic/nephtali_3_0_3.zip</id>
 <link rel="alternate" type="text/html" href="http://code.google.com/p/nephtali/downloads/detail?name=nephtali_3_0_3.zip" />
 <title>
 nephtali_3_0_3.zip (25.1 KB)
 </title>
 <author>
 <name>simpleshot</name>
 </author>
 <content type="html">

<pre>
nephtali_3_0_3

Labels: 
 Featured
 Type-Archive

<a href="http://nephtali.googlecode.com/files/nephtali_3_0_3.zip">Download</a>
</pre>
 </content>
</entry>
</feed>
EOD;

$arr = n\xml\parse(
		$xml_str, 
		$result = array(), 
		$xpath_functions = array(
			'/feed/entry' => function($node, $result)
			{
				$row['link'] = (string)$node->link['href'];
				$row['title'] = (string)$node->title;
				$result[] = $row;
				return $result;
			}
		)
);