<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rayhan's blog (raynux.com) &#187; class</title>
	<atom:link href="http://raynux.com/blog/tag/class/feed/" rel="self" type="application/rss+xml" />
	<link>http://raynux.com/blog</link>
	<description>Rayhan's Personal Web Blog Site</description>
	<lastBuildDate>Fri, 16 Oct 2009 06:07:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>RayFeedReader &#8211; PHP class for parsing RSS and Atom Feed</title>
		<link>http://raynux.com/blog/2009/09/02/rayfeedreader-php-class-for-parsing-rss-and-atom-feed/</link>
		<comments>http://raynux.com/blog/2009/09/02/rayfeedreader-php-class-for-parsing-rss-and-atom-feed/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 18:35:09 +0000</pubDate>
		<dc:creator>rayhan</dc:creator>
				<category><![CDATA[FEED]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ATOM]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[RSS]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://raynux.com/blog/?p=147</guid>
		<description><![CDATA[RayFeedReader, A Simple and Easy SimpleXML based feed reader class using PHP. First of all it&#8217;s another reinvention of wheel. This class is designed to provide quick access to any XML based RSS feed and it&#8217;s content. Usages are very simple and require only one line of code. Html rendering functionality is provided through separate [...]]]></description>
			<content:encoded><![CDATA[<p><strong>RayFeedReader</strong>, A Simple and Easy SimpleXML based feed reader class using PHP.</p>
<p>First of all it&#8217;s another reinvention of wheel. This class is designed to provide quick access to any XML based RSS feed and it&#8217;s content. Usages are very simple and require only one line of code. Html rendering functionality is provided through separate pluggable widget rendering class which can be extended easily. SimpleXML is used by default to load and fetch feed url but can be used CURL using rayHttp class. All or any CURL options can be set for HTTP request. It can auto detect feed type and supports RSS 0.92, RSS 2.0 and Atom feeds. </p>
<p><strong>Features:</strong></p>
<p>- Read feeds content into an array<br />
- Supports for RSS 0.92, RSS 2.0 and Atom feed<br />
- Detect feed type automatically, also can be set manually.<br />
- Support pluggable html widget rendering class<br />
- Can render html widget through optional RayFeedWidget class or your own extended class.<br />
- Easily configurable &amp; can work without any configuration.<br />
- Simple &amp; Easy to use from anywhere in your application with a single line of code.<br />
- Support Singleton pattern<br />
- By default SimpleXML is used as http client,<br />
- Support Custom CURL request, may be used to extends functionality through rayHttp class.<br />
- Light Weight</p>
<p>Methods Available (This class provides):<br />
- parse()<br />
- getData()<br />
- widget()</p>
<p><strong>Class:</strong></p>
<p>File: <strong>rayfeedreader.php</strong></p>
<pre><code>&lt;?php

    /**
     * RayFeedReader
     *
     * SimpleXML based feed reader class. A very specific feed reader designed
     * to working with no or little configurations.
     *
     * - This class can read an rss feed into array from a given url.
     * - Also can render html widget with plugable RayFeedWidget Class.
     *
     * Supports following feed types:
     *  - RSS 0.92
     *  - RSS 2.0
     *  - Atom
     *
     * Configuration Options
     *  - array
     *      - url: (string)
     *          - feed url
     *
     *      - httpClient: (string)
     *          - default SimpleXML
     *          - value rayHttp or SimpleXML
     *
     *      - type: ([optional] string
     *          - auto detect
     *          - value rss or rss2 or atom
     *
     *      - widget: ([optional] string)
     *          - feed widget class name for rendering html
     *
     *      - rayHttp: (array)
     *          - only if httpClient is set to rayHttp
     *          - rayHttp Options if you want to modify rayHttml CURL options
     *          - generally not required.
     *
     *
     *
     *
     * @version 1.0
     * @author Md. Rayhan Chowdhury
     * @package rayFeedReader
     * @license GPL
     */
    Class RayFeedReader{

        /**
         * Self Instance for Singleton Pattern
         *
         * @var object
         * @access protected
         */
        static private  $__instance;

        /**
         * Instance of Parser Class.
         *
         * @var object Parser Class
         * @access protected
         */
        Protected       $_Parser;

        /**
         * Feed Url
         *
         * @var string feed url
         * @access protected
         */
        protected       $_url;

        /**
         * Runtime Options for reader
         *
         * @var array
         * @access protected
         */
        protected       $_options = array('rayHttp' => array());

        /**
         * Type of feed to be parsed.
         *
         * @var string
         * @access protected
         */
        protected       $_type = "rss";

        /**
         * HttpClient to be used for loading feed content.
         *
         *  - default SimpleXML
         *
         * @var string 'SimpleXML' or 'rayHttp'
         * @access protected
         */
        protected       $_httpClient = "SimpleXML";

        /**
         * Widget Class Name
         *
         * @var string
         * @access protected
         */
        protected       $_widget;

        /**
         * Parsed result data
         *
         * @var array
         * @access protected
         */
        protected       $_content;

        /**
         * Class construct
         *
         * @param array $options
         */
        function __construct($options = array()) {
            $this->setOptions($options);
        }

        /**
         * Get Instance of the class.
         *
         * @param array $options
         * @return object self instance.
         * @access public
         * @static
         */
        static function &#038;getInstance($options = array()) {
            if (is_null(self::$__instance)) {
                self::$__instance = new self($options);
            }
            return self::$__instance;
        }

        /**
         * Set Options for the class
         *
         *
         * @param array $options
         * @return object self instance
         * @access public
         */
        function &#038;setOptions($options) {
            if (!empty($options['url'])) {
                $this->_url = $options['url'];
            }

            if (!empty($options['type'])) {
                $this->_type = $options['type'];
            }

            if (!empty($options['httpClient'])) {
                $this->_httpClient = $options['httpClient'];
            }

            if (!empty($options['widget'])) {
                $this->_widget = $options['widget'];
            }

            $this->_options = array_merge($this->_options, $options);

            return $this;
        }

        /**
         * Parse feed contents into an array and return self object
         *
         * @return object self instance
         * @access public
         */
        function &#038;parse() {
            /**
             * Get/load content
             */
             switch ($this->_httpClient) {
                 case 'SimpleXML':
                     $content = new SimpleXMLElement($this->_url, LIBXML_NOCDATA, true);
                     break;

                 case 'rayHttp':

                     $content = RayHttp::getInstance()->setOptions($this->_options['rayHttp'])->get($this->_url);

                     if (!empty($content)) {
                        $content = new SimpleXMLElement($content, LIBXML_NOCDATA);
                     }
                     break;
             }

             if (empty($content)) {
                 trigger_error("XML format is invalid or broken.", E_USER_ERROR);
             }

            /**
             * Detect Feed Type
             */

             if (empty($this->_type)) {

                    switch ($content->getName()) {
                        case 'rss':
                            foreach ($content->attributes() as $attribute) {
                                if ($attribute->getName() == 'version') {
                                    if ('2.0' == $attribute) {
                                        self::setOptions(array('type' => 'rss2'));
                                    } elseif (in_array($attribute, array('0.92', '0.91'))) {
                                        self::setOptions(array('type' => 'rss'));
                                    }
                                }
                            }
                            break;

                        case 'feed':
                            self::setOptions(array('type' => 'atom'));

                            break;
                    }

             }

             if (!in_array($this->_type, array('rss', 'rss2', 'atom'))) {

                  trigger_error("Feed type is either invalid or not supported.", E_USER_ERROR);

                  return false;
             }

            /**
             * Parse Feed Content
             */
            switch ($this->_type) {
                case 'rss':
                    $content = $this->parseRss($content);
                    break;

                case 'rss2':
                    $content = $this->parseRss2($content);
                    break;

                case 'atom':
                    $content = $this->parseAtom($content);
                    break;
            }

             if (empty($content)) {
                 trigger_error("No content is found.", E_USER_ERROR);
             }

             $this->_content = $content;

             return $this;

        }

        /**
         * Get Array of Parsed XML feed data.
         *
         * @return array parsed feed content.
         * @access public
         */
        function getData() {
            return $this->_content;
        }

        /**
         * Return html widget based rendered by widget class
         *
         *
         * @param array $options for html widget class
         * @return string html widget
         * @access public
         */
        function widget($options = array('widget' => 'brief')) {
            if (!empty($this->_widget) &#038;&#038; !empty($this->_content)) {
                $Widget = new $this->_widget;

                return $Widget->widget($this->_content, $options);

             } else {
                 return false;
             }
        }

        /**
         * Parse feed xml into an array.
         *
         * @param object $feedXml SimpleXMLElementObject
         * @return array feed content
         * @access public
         */
        function parseRss($feedXml) {
            $data = array();

            $data['title'] = $feedXml->channel->title . '';
            $data['link'] = $feedXml->channel->link . '';
            $data['description'] = $feedXml->channel->description . '';
            $data['parser'] = __CLASS__;
            $data['type'] = 'rss';

            foreach ($feedXml->channel->item as $item) {
                $data['items'][] = array(
                                        'title' =>  $item->title . '',
                                        'link' =>   $item->link . '',
                                        'description' => $item->description . '',
                                    );
            }

            return $data;
        }

        /**
         * Parse feed xml into an array.
         *
         * @param object $feedXml SimpleXMLElementObject
         * @return array feed content
         * @access public
         */
        function parseRss2($feedXml) {
            $data = array();

            $data['title'] = $feedXml->channel->title . '';
            $data['link'] = $feedXml->channel->link . '';
            $data['description'] = $feedXml->channel->description . '';
            $data['parser'] = __CLASS__;
            $data['type'] = 'rss2';

            $namespaces = $feedXml->getNamespaces(true);
            foreach ($namespaces as $namespace => $namespaceValue) {
                $feedXml->registerXPathNamespace($namespace, $namespaceValue);
            }

            foreach ($feedXml->channel->item as $item) {
                $categories = array();
                foreach ($item->children() as $child) {
                    if ($child->getName() == 'category') {
                        $categories[] = (string) $child;
                    }
                }

                $author = null;
                if (!empty($namespaces['dc']) &#038;&#038; $creator = $item->xpath('dc:creator')) {
                    $author = (string) $creator[0];
                }

                $content = null;
                if (!empty($namespaces['encoded']) &#038;&#038; $encoded = $item->xpath('content:encoded')) {
                    $content = (string) $encoded[0];
                }

                $data['items'][] = array(
                                        'title' =>  $item->title . '',
                                        'link' =>   $item->link . '',
                                        'date' =>   date('Y-m-d h:i:s A', strtotime($item->pubDate . '')),
                                        'description' => $item->description . '',
                                        'categories' => $categories,
                                        'author' => array( 'name' => $author),
                                        'content' => $content,

                                    );

            }

            return $data;
        }

        /**
         * Parse feed xml into an array.
         *
         * @param object $feedXml SimpleXMLElementObject
         * @return array feed content
         * @access public
         */
        function parseAtom($feedXml) {
            $data = array();

            $data['title'] = $feedXml->title . '';
            foreach ($feedXml->link as $link) {
                    $data['link'] = $link['href'] . '';
                break;
            }

            $data['description'] = $feedXml->subtitle . '';
            $data['parser'] = __CLASS__;
            $data['type'] = 'atom';

            foreach ($feedXml->entry as $item) {
                foreach ($item->link as $link) {
                    $itemLink = $link['href'] . '';
                    break;
                }

                $categories = array();
                foreach ($item->category as $category) {
                    $categories[] = $category['term'] . '';
                }

                $data['items'][] = array(
                                        'title' =>  $item->title . '',
                                        'link' =>   $itemLink . '',
                                        'date' =>   date('Y-m-d h:i:s A', strtotime($item->published . '')),
                                        'description' => $item->summary . '',
                                        'content' => $item->content . '',
                                        'categories' => $categories,
                                        'author' => array('name' => $item->author->name . '', 'url' => $item->author->uri . ''),
                                        'extra' => array('contentType' => $item->content['type'] . '', 'descriptionType' => $item->summary['type'] . '')
                                    );
            }

            return $data;
        }

    }
?&gt;</code></pre>
<p>External feed widget class to get rendered html widget. </p>
<p>File: <strong>rayfeedwidget.php</strong></p>
<pre><code>&lt;?php

    /**
     * Feed Widget Interface
     *
     * @version 1.0
     * @author Md. Rayhan Chowdhury
     * @package rayFeedReader
     * @license GPL
     */
    interface RayFeedWidget_Interface{
        /**
         * Public widget method
         *
         * @param &lt;type> $data
         * @param <type> $options
         * @return string html
         */
        public function widget($data, $options = array());
    }

    /**
     * Widget Plugin Class for RayFeedReader
     *
     * Render html widget for feed reader based on options
     *
     * config options
     *  - array
     *      - widget:
     *          - optional string
     *          - value 'brief' or 'compact' or 'detail'
     *      - showTitle
     *          - boolean
     *          - whether add blog title or not.
     *
     * @version 1.0
     * @author Md. Rayhan Chowdhury
     * @package rayFeedReader
     * @license GPL
     */
    class RayFeedWidget implements RayFeedWidget_Interface{

        /**
         * HTML widget structure
         *
         * @var array
         * @access public
         */
        public $html = array('brief' => "&lt;div class=\"feed-item feed-brief\"&gt;\n
                                            &lt;div class=\"feed-item-title\"&gt;\n
                                                &lt;h3&gt;&lt;a href='%s'&gt;%s&lt;/a&gt;&lt;/h3&gt;\n
                                                &lt;div class='feed-item-date'&gt;%s&lt;/div&gt;\n
                                            &lt;/div&gt;\n
                                            &lt;div class=\"feed-item-description\"&gt;%s&lt;/div&gt;\n
                                        &lt;/div&gt;",

                                'compact' => "&lt;div class=\"feed-item feed-compact\"&gt;\n
                                    &lt;div class=\"feed-item-title\"&gt;\n
                                        &lt;h3&gt;&lt;a href='%s'&gt;%s&lt;/a&gt;&lt;/h3&gt;\n
                                        &lt;div class='feed-item-date'&gt;%s&lt;/div&gt;\n
                                    &lt;/div&gt;\n
                                &lt;/div&gt;",

                                'detail' => "&lt;div class=\"feed-item feed-detail\"&gt;\n
                                    &lt;div class=\"feed-item-title\"&gt;\n
                                        &lt;h3&gt;&lt;a href='%s'&gt;%s&lt;/a&gt;&lt;/h3&gt;\n
                                        &lt;div class='feed-item-date'&gt;%s&lt;/div&gt;\n
                                    &lt;/div&gt;\n
                                    &lt;div class=\"feed-item-content\"&gt;%s&lt;/div&gt;\n
                                &lt;/div&gt;",
                            );

        /**
         * Return html widget based rendered by widget class
         *
         * @param <type> $data
         * @param <type> $options
         * @return <type>
         */
        function widget($data, $options = array('widget' => 'brief')) {
            switch ($options['widget']) {

                case 'compact':
                    return $this->widgetCompact($data, $options);
                    break;

                case 'detail':
                    return $this->widgetDetail($data, $options);
                    break;

                case 'brief':
                default:
                    return $this->widgetBrief($data, $options);
                    break;
            }
        }

        /**
         * Render feed widget with title and date only
         *
         * @param <type> $data
         * @param <type> $options
         * @return <type>
         */
        function widgetCompact($data, $options = array()) {
            if (empty($data['items'])) {
              return false;
            }

            $out = array();
            foreach ($data['items'] as $item) {
                if (empty($item['date'])) {
                    $item['date'] = '';
                }
                $out[] = sprintf($this->html['compact'], $item['link'], $item['title'], $item['date']);

            }

            $title = '';
            if (empty($options['showtitle'])) {
                $title = sprintf("&lt;div class='feed-title'&gt;&lt;h2&gt;%s&lt;/h2&gt;&lt;hr&gt;%s&lt;/div&gt;\n", $data['title'], $data['description']);
            }

            $out = "&lt;div class='feed-container'&gt;\n"  . $title . join(" \n", $out) . "&lt;/div&gt;";

            return $out;
        }

        /**
         * Render feed widget with title, date &#038; description
         *
         * @param <type> $data
         * @param <type> $options
         * @return <type>
         */
        function widgetBrief($data, $options = array()) {
            if (empty($data['items'])) {
              return false;
            }

            $out = array();

            foreach ($data['items'] as $item) {
                if (empty($item['date'])) {
                    $item['date'] = '';
                }

                if (empty($item['description'])) {
                        $item['description'] = $item['content'];
                }

                $out[] = sprintf($this->html['brief'], $item['link'], $item['title'], $item['date'], $item['description']);

            }

            $title = '';
            if (empty($options['showtitle'])) {
                $title = sprintf("&lt;div class='feed-title'&gt;&lt;h2&gt;%s&lt;/h2&gt;&lt;hr&gt;%s&lt;/div&gt;\n", $data['title'], $data['description']);
            }

            $out = "&lt;div class='feed-container'&gt;\n"  . $title . join(" \n", $out) . "&lt;/div&gt;";

            return $out;
        }

        /**
         * Render blog widget with title, date &#038; content
         *
         * @param <type> $data
         * @param <type> $options
         * @return <type>
         */
        function widgetDetail($data, $options = array()) {
            if (empty($data['items'])) {
              return false;
            }

            $out = array();
            foreach ($data['items'] as $item) {
                if (empty($item['date'])) {
                    $item['date'] = '';
                }
                if (empty($item['content'])) {
                    $item['content'] = $item['description'];
                }
                $out[] = sprintf($this->html['detail'], $item['link'], $item['title'], $item['date'], $item['content']);

            }

            $title = '';
            if (empty($options['showtitle'])) {
                $title = sprintf("&lt;div class='feed-title'&gt;&lt;h2&gt;%s&lt;/h2&gt;&lt;hr&gt;%s&lt;/div&gt;\n", $data['title'], $data['description']);
            }

            $out = "&lt;div class='feed-container'&gt;\n"  . $title . join(" \n", $out) . "&lt;/div&gt;";

            return $out;
        }
    }
?&gt;</code></pre>
<p>Usage Example: some quick examples are given below to introduce you with the class and it&#8217;s methods. </p>
<p>File: <strong>example.php</strong></p>
<pre><code>&lt;?php

    /**
     * Example Usage or RayFeedReader
     */

    require_once('rayfeedreader.php');   

    /**
     * get Instance
     */
    $reader1 = RayFeedReader::getInstance();
    $reader2 = RayFeedReader::getInstance($options);
    $reader3 = new RayFeedReader();
    $reader4 = new RayFeedReader($options);

    /**
     * get data from a feed url
     */
    $options = array('url' => 'http://example.com/feed');

    $feedData = RayFeedReader::getInstance($options)->parse()->getData();

    // Or options can be set anytime using setOptions method.
    $feedData = RayFeedReader::getInstance()->setOptions($options)->parse()->getData();

    /**
     * Get html widget
     */

    $options = array(
                        'url' => 'http://example.com/feed',
                        'widget' => 'RayFeedWidget',
                    );

    /**
     * Load rayFeedWidget class file
     */
    require_once('rayfeedwidget.php');

    $html = RayFeedReader::getInstance()->setOptions($options)->parse()->widget();

    // OR with widget options.
    $widgetOptions = array('widget' => 'detail', 'showTitle' => true);

    $html = RayFeedReader::getInstance()->setOptions($options)->parse()->widget($widgetOptions);

    /**
     * Full options
     */
    $options = array(
                        'url' => 'http://example.com/feed',
                        'widget' => 'RayFeedWidget',
                        'httpClient' => 'rayHttp',
                        'type' => 'atom',
                    );

    /**
     * Load rayHttp class file.
     */
    require_once("rayhttp.php");    

    /**
     * Html widget with full options
     */
    $html = RayFeedReader::getInstance()->setOptions($options)->parse()->widget();

    /**
     * Get Feed Data with full options
     */
    $feedData = RayFeedReader::getInstance($options)->parse()->getData();
?&gt;</code></pre>
<p>Please let me know if you find this class helpful for you..</p>
<blockquote><p>
<strong>Class Update:</strong></p>
<p>An updated version of this class and example script are posted at PHPClasses.org, <a href="http://www.phpclasses.org/browse/package/5652.html">http://www.phpclasses.org/browse/package/5652.html</a>. Please use class from <a href="http://www.phpclasses.org">PHPClasses.org</a> for bug fixed latest version.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://raynux.com/blog/2009/09/02/rayfeedreader-php-class-for-parsing-rss-and-atom-feed/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Convert a Multidimensional Array Into Single Dimension</title>
		<link>http://raynux.com/blog/2009/06/28/convert-a-multidimensional-array-into-single-dimension/</link>
		<comments>http://raynux.com/blog/2009/06/28/convert-a-multidimensional-array-into-single-dimension/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 03:51:10 +0000</pubDate>
		<dc:creator>rayhan</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://raynux.com/blog/?p=127</guid>
		<description><![CDATA[RayArray is a array utility class. I have wrapped three static functions for converting multidimensional configuration data. It is very much useful when working with configuration data. I have used this class in one of my project to store arbitrary configuration data just like windows registry data. File: rayarray.php &#60;?php /** * RayArray arrays utility [...]]]></description>
			<content:encoded><![CDATA[<p><strong>RayArray</strong> is a array utility class.</p>
<p>I have wrapped three static functions for converting multidimensional configuration data. It is very much useful when working with configuration data. I have used this class in one of my project to store arbitrary configuration data just like windows registry data.</p>
<p>File: <strong>rayarray.php</strong></p>
<pre><code>&lt;?php
/**
* RayArray arrays utility class
*
* This class provides configuration array handling funcionalities,
* may be usefull when dealing with configuration data.
*
* Usage: using this class you can convert a multidimensional configuration
* array into a single dimension array ready to store into sql table/ flat file.
*
* methods available are
*  - shorten() - static
*  - unshorten() - static
*  - subarray() - static
*
* @package     raynux
* @subpackage  raynux.lab.array
* @version     1.0
* @author      Md. Rayhan Chowdhury
* @email       ray@raynux.com
* @website     www.raynux.com
* @license     GPL
*/
class RayArray{
/**
 * Shorten an multidimensional array into a single dimensional array concatenating all keys with separator.
 *
 * @example array('country' =&gt; array(0 =&gt; array('name' =&gt; 'Bangladesh', 'capital' =&gt; 'Dhaka')))
 *          to array('country.0.name' =&gt; 'Bangladesh', 'country.0.capital' =&gt; 'Dhaka')
 *
 * @param array $inputArray, arrays to be marged into a single dimensional array
 * @param string $path, Default Initial path
 * @param string $separator, array key path separator
 * @return array, single dimensional array with key and value pair
 * @access public
 * @static
 */
static public function shorten(array $inputArray, $path = null, $separator = "."){
   $data = array();
   if (!is_null($path)) {
      $path = $path . $separator;
   }

   if (is_array($inputArray)) {
      foreach ($inputArray as $key =&gt; &amp;$value) {
         if (!is_array($value)) {
            $data[$path . $key] = $value;
         } else {
            $data = array_merge($data, self::shorten($value, $path . $key, $separator));
         }
      }
   }

   return $data;
}

/**
 * Unshorten a single dimensional array into multidimensional array.
 *
 * @example array('country.0.name' =&gt; 'Bangladesh', 'country.0.capital' =&gt; 'Dhaka')
 *          to array('country' =&gt; array(0 =&gt; array('name' =&gt; 'Bangladesh', 'capital' =&gt; 'Dhaka')))
 *
 * @param array $data data to be converted into multidimensional array
 * @param string $separator key path separator
 * @return array multi dimensional array
 * @access public
 * @static
 */
static public function unshorten($data, $separator = '.'){
   $result = array();

   foreach ($data as $key =&gt; $value){
      if(strpos($key, $separator) !== false ){
         $str = explode($separator, $key, 2);
         $result[$str[0]][$str[1]] = $value;
         if(strpos($str[1], $separator)){
            $result[$str[0]] = self::unshorten($result[$str[0]], $separator);
         }
      }else{
         $result[$key] = is_array($value)?  self::unshorten($value, $separator) : $value;
      }
   }
   return $result;
}

/**
 * Get part of array from a multidimensional array specified by concatenated keys path.
 *
 * @example
 *          path = "0.name"
 *          data =
 *          array(
 *                  array('name' =&gt; array('Bangladesh', 'Srilanka', 'India', 'Pakistan')),
 *                  array('help' =&gt; 'help.php'),
 *                  'test' =&gt; 'value',
 *                  10 =&gt;
 *          false)
 *          will return array('Bangladesh', 'Srilanka', 'India', 'Pakistan')
 * @param string $path
 * @param array $data
 * @param string $separator path separator default '.'
 * @return mixed and return NULL if not found.
 * @access public
 * @static
 */
static public function subarray($path, &amp;$data, $separator = '.') {
   if (strpos($path, $separator) === false) {
      if (isset($data[$path])) {
         return $data[$path];
      }
   } else {
      $keys = explode($separator, $path, 2);
      if (array_key_exists($keys[0], $data)) {
         return self::subarray($keys[1], $data[$keys[0]], $separator);
      }
   }
}
}
?&gt;</code></pre>
<p>Please drop me a line if you find this class useful or you have a different opinion.</p>
]]></content:encoded>
			<wfw:commentRss>http://raynux.com/blog/2009/06/28/convert-a-multidimensional-array-into-single-dimension/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Http Client Class for PHP development</title>
		<link>http://raynux.com/blog/2009/06/13/http-client-class-for-php-development/</link>
		<comments>http://raynux.com/blog/2009/06/13/http-client-class-for-php-development/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 07:01:35 +0000</pubDate>
		<dc:creator>rayhan</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://raynux.com/blog/?p=99</guid>
		<description><![CDATA[RayHttp, A Simple Http Client Class for PHP Development. This class is designed to provide quick http reqest method to access external website. A CURL alternative to php native file_get_contents method. It can work without any configuration and can be called anywhere is your application using singleton design pattern. Unlike other Http client class in [...]]]></description>
			<content:encoded><![CDATA[<p><strong>RayHttp</strong>, A Simple Http Client Class for PHP Development.</p>
<p>This class is designed to provide quick http reqest method to access external website. A CURL alternative to php native file_get_contents method. It can work without any configuration and can be called anywhere is your application using singleton design pattern. Unlike other Http client class in php, this is lightweight, simple and easy to use and configure. If you need more functionality you can extend the class. CURL request is fully customizable through setCurlOptions() method.</p>
<p>This class is suitable for those project which is not built on a PHP Framework. Usually all frameworks provide a built in Http Client Object.</p>
<p><strong>Features:</strong></p>
<p>- General purpose http request class.<br />
- Supports GET &amp; POST request Method.<br />
- For GET Request both CURL &amp; PHP native file_get_contents are available.<br />
- By default CURL is used for GET Request.<br />
- Easily configurable &amp; can work without any configuration.<br />
- Simple &amp; Easy to use from anywhere in your application with a single line of code.<br />
- Request through CURL fully configurable with all possible curl options, so it&#8217;s up to you.<br />
- Encode given URL Automatically, may be disabled.<br />
- Supports POST requests with a user defined array or serialised string of form values.<br />
- Supports GET requests with a user defined parameter array.<br />
- Support Singleton pattern<br />
- Support Custom CURL request, may be used to extends functionality.<br />
- Light Weight</p>
<p>Methods Available (This class provides):</p>
<p>- get()<br />
- post()<br />
- curlExecute()<br />
- encodeUrl()</p>
<p><strong>Class:</strong></p>
<p>File: <strong>rayhttp.php</strong></p>
<pre><code>&lt;?php
/*	SVN FILE: $Id: rayhttp.php 113 2008-06-15 04:30:19Z rayhan $	 */
/**
 * HTTP Client Class.
 *
 * A basic HTTP Client desinged for php developer.
 * - CURL
 * - Native php method
 *
 *	PHP Version 5
 *
 *
 *	@copyright		Copyright 2006-2008, Md. Rayhan Chowdhury
 *	@package		raynux
 *	@subpackage		raynux.lab.http
 * 	@since			version 1.0
 *	@version		$Revision: 113 $
 * 	@modifiedby		$LastChangedBy: rayhan $
 *	@lastModified	$Date: 2008-06-15 10:30:19 +0600 (Sun, 15 Jun 2008) $
 *	@author			$Author: rayhan $
 *	@url			$HeadURL: http://localhost/svn/raynux/trunk/labs/rayhttp.php $
 *	@website		www.raynux.com
 *  @license 		GPL
 */

/**
 * HTTP Client Class.
 *
 * A basic HTTP Client desinged for php developer.
 * - CURL
 * - Native php method
 *
 *
 * @todo add utf-8 conversion.
 * @todo add plugins functionality
 *
 *
 * @package raynux
 * @subpackage raynux.lab.http
 * @version 1.0
 * @since version 1.0
 * @author Md. Rayhan Chowdhury
 */
class RayHttp{

	/**
	 * Hold runtime instance of self
	 *
	 * @var array of self instances
	 * @access private
	 * @static
	 */
	static private $__instances;

	/**
	 * Curl Instance
	 *
	 * @var object Curl instance
	 * @access protected
	 */
	protected 	$_curlInstance = null;

	/**
	 * Default configuration for the crawler.
	 *
	 * @var array
	 * @access private
	 */
	private 	$__defaultConfigs = array(
                    'client' =&gt; 'curl',
                    'encodeUrl' =&gt; true,
                    'curlOptions' =&gt; array(
                        CURLOPT_SSL_VERIFYPEER =&gt; 0,
                        CURLOPT_RETURNTRANSFER =&gt; 1,
                        CURLOPT_FOLLOWLOCATION =&gt; 1,
                        CURLOPT_ENCODING =&gt; "",
                        CURLOPT_USERAGENT =&gt; "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.5) Gecko/2008120121 Firefox/3.0.5",
                        CURLOPT_COOKIESESSION =&gt; 1,
                        CURLOPT_AUTOREFERER =&gt; 1,
                        CURLOPT_CONNECTTIMEOUT =&gt; 120,
                        CURLOPT_AUTOREFERER =&gt; 120,
                        CURLOPT_TIMEOUT =&gt; 120,
                        CURLOPT_MAXREDIRS =&gt; 10,
                        CURLOPT_COOKIEFILE =&gt; 'cookiefile',
                        CURLOPT_COOKIEJAR =&gt; 'cookiefile',
                    ),
                );

	/**
	 * Hold runtime configuration.
	 *
	 *
	 * @var array
	 * @access protected
	 */
	protected 	$_configs = array();

	/**
	 * Class Constructor
	 *
	 * @param array $configs
	 * @access public
	 * @return unknown
	 */
	function __construct($configs = array()){
		if (!empty($configs)) {
			$this-&gt;setOptions($configs);
		} else {
			$this-&gt;setOptions($this-&gt;__defaultConfigs);
		}
	}

	/**
	 * Configure the class.
	 *
	 * @param array $configs, configuration data.
	 * @return unknown
	 * @access public
	 */
	public function &amp;setOptions($configs){
		$this-&gt;_configs = array_merge($this-&gt;__defaultConfigs, $configs);

		return $this;
	}

	/**
	 * Get Curl Instance.
	 *
	 * @return object curl instance
	 * @access protected
	 */
	protected function &amp;_getCurlInstance() {
		if ($this-&gt;_curlInstance == null) {
			$this-&gt;_curlInstance = curl_init();
			$this-&gt;setCurlOptions($this-&gt;_configs['curlOptions']);
		}
		return $this-&gt;_curlInstance;
	}

	/**
	 * Set Curl Options from array
	 *
	 * @param array $options
	 * @return object | this
	 * @access public
	 */
	public function &amp;setCurlOptions($options = array()) {
		$c = $this-&gt;_getCurlInstance();
		if (function_exists('curl_setopt_array')) {
			curl_setopt_array($c, $options);
		} else {
			foreach ($options as $key =&gt; $value) {
				curl_setopt($c, $key, $value);
			}
		}
		return $this;
	}

	/**
	 * Execute curl library function.
	 *
	 * @param string $url
	 * @param string $method, http method, 'get' or 'post'
	 * @param string|array $postFields, form data
	 * @return string | curl response object
	 * @access public
	 */
	public function curlExecute($url, $method = 'get', $postFields = null){
		$c = $this-&gt;_getCurlInstance();
		if ($method === 'get') {
			$this-&gt;setCurlOptions(array(CURLOPT_URL =&gt; $url,
                                        CURLOPT_POST =&gt; false,
                                        CURLOPT_HTTPGET =&gt; 1));

		} elseif ($method === 'post') {
			$this-&gt;setCurlOptions(array(CURLOPT_URL =&gt; $url,
                                        CURLOPT_POST =&gt; true,
                                        CURLOPT_HTTPGET =&gt; 0,
                                        CURLOPT_POSTFIELDS =&gt; $postFields));

		} else {
			$this-&gt;setCurlOptions(array(CURLOPT_URL =&gt; $url));

		}
		return curl_exec($c);
	}

	/**
	 * Encode url with urlencode function for unencoded character.
	 *
	 * @param string $url urls to be encoded.
	 * @param string $callback function name as callback function, 'urlencode' or 'raw_urlencode'
	 * @return string encoded url.
	 * @access public
	 */
	public function encodeUrl($url, $callback = 'urlencode') {
		if ($pathOfset = strpos($url, '/', (strpos($url, '://') + 3))) {

			extract(parse_url($url));

			$path = implode('/', array_map($callback, explode('/', $path)));
			$url = substr($url, 0, $pathOfset) . $path;

			if (!empty($query)) {
				parse_str($query, $query);
				$query = http_build_query(array_map($callback, $query));
				$query = preg_replace('@(\=($|(&amp;)))@is', '\3', $query);			// remove tailing = sign from empty variable.
				$url = $url . "?" . $query;
			}
		}

		return $url;
	}

    /**
     * Get Self Instance.
     *
     * @param string $name, name of the instance, default value is 'default'
     * @param array $configs, configuration array for the instance
     * @return object, self instance
	 * @access public
     * @static
     */
    static public function &amp;getInstance($name = 'default', $configs = array()){
    	if (is_null(self::$__instances[$name])) {
    		self::$__instances[$name] = new self($configs);
    	}
    	return self::$__instances[$name];
    }

	/**
	 * Get url contents using GET MEthod.
	 *
	 * @param string $url
	 * @param string|array $getData, get data in serialized string or array format.
	 * @return string
	 * @access public
	 */
    public function get($url, $getData = null){
    	if (!is_null($getData)) {
    		if (is_array($getData)) {
    			$getData = http_build_query($getData);
    		}
    		if (strpos($url, '?') === false) {
    			$url .= '?';
    		}
    		$url .= $getData;
    	}

    	if ($this-&gt;_configs['encodeUrl']) {
    		$url = $this-&gt;encodeUrl($url);
    	}

    	if ($this-&gt;_configs['client'] === 'php') {
    		return file_get_contents($url);
    	}
    	return $this-&gt;curlExecute($url);
    }

    /**
     * Get URL contents using POST method.
     *
     * @param string $url
     * @param string|array $postData, form data in serialized string or array format.
     * @return string
     * @access public
     */
    public function post($url, $postData = null) {
    	if (is_array($postData)) {
    		$postData = http_build_query($postData);
    	}

    	if ($this-&gt;_configs['encodeUrl']) {
    		$url = $this-&gt;encodeUrl($url);
    	}

    	return $this-&gt;curlExecute($url, 'post', $postData);
    }
}
</code></pre>
<p>
<strong>Usage Example:</strong><br />
File: <strong>example.php</strong></p>
<pre><code>&lt;?php
/**
 * HTTP Client Class Example Script.
 *
 * Example of RayHttp Class Object.
 *
 *	PHP Version 5
 *
 *
 *	@copyright		Copyright 2006-2008, Md. Rayhan Chowdhury
 *	@package		raynux
 *	@subpackage		raynux.lab.http
 * 	@since			version 1.0
 *	@version		$Revision: 113 $
 * 	@modifiedby		$LastChangedBy: rayhan $
 *	@lastModified	$Date: 2008-06-15 10:30:19 +0600 (Sun, 15 Jun 2008) $
 *	@author			$Author: rayhan $
 *	@url			$HeadURL: http://localhost/svn/raynux/trunk/labs/example.php $
 *	@website		www.raynux.com
 *  @license 		GPL
 */

/**
 * Load the http client.
 */
require_once("rayhttp.php");

/**
 * METHOD GET.
 */

/**
 * Example 1
 *
 * using default configuration
 * default method is curl.
 * use as a singleton object.
 */
$content = RayHttp::getInstance()-&gt;get("http://google.com");
$content = RayHttp::getInstance()-&gt;get("http://google.com/search", array('q' =&gt; 'rayhttp'));
$content = RayHttp::getInstance()-&gt;get("http://google.com/search?q=rayhttp");

/**
 * Example 2
 *
 * using default configuration but using php native file_get_contetns method.
 * use as a singleton object.
 * static method.
 */
$content = RayHttp::getInstance()-&gt;setOptions(array('client' =&gt; 'php'))-&gt;get("http://google.com");
$content = RayHttp::getInstance()-&gt;setOptions(array('client' =&gt; 'php'))-&gt;get("http://google.com/search", array('q' =&gt; 'rayhttp'));
$content = RayHttp::getInstance()-&gt;setOptions(array('client' =&gt; 'php'))-&gt;get("http://google.com/search?q=rayhttp");

/**
 * Example 3
 *
 * Take Instance Of the object
 */
$http = new RayHttp();
$content = $http-&gt;get("http://google.com");
$content = $http-&gt;get("http://google.com/search", array('q' =&gt; 'rayhttp'));
$content = $http-&gt;get("http://google.com/search?q=rayhttp");

/**
 * METHOD POST.
 */

/**
 * Example 4
 *
 * using default configuration
 */
$content = RayHttp::getInstance()-&gt;post("http://example.com/", array('name' =&gt; 'rayhttp', 'location' =&gt; 'dhaka, bangladesh'));

/**
 * Multiple Instance &amp; Configuration.
 */
RayHttp::getInstance('default', $configs);
RayHttp::getInstance('default2', $configs);

$http = RayHttp::getInstance(); // get default instance
$http2 = RayHttp::getInstance('default2'); // get default2 instance

$http3 = RayHttp::getInstance('default3', $configs); // get default 3 instance
$http3-&gt;setOptions($configs); // reconfigure default3 instance;

/**
 * Specify Proxy
 */
RayHttp::getInstance('c')-&gt;setCurlOptions(array(CURLOPT_PROXY =&gt; '172.19.79.1:3128'))-&gt;get("http://www.google.com");

</code></pre>
<p>Rate this class at phpclasses.org: <a href="http://www.phpclasses.org/rayhttpclient">http://www.phpclasses.org/rayhttpclient</a></p>
]]></content:encoded>
			<wfw:commentRss>http://raynux.com/blog/2009/06/13/http-client-class-for-php-development/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
