Tuesday, May 3, 2011

Parsing Params from a UI in PHP

I've seen a lot of this out there, and seen a variety of scripts that...well...just don't work. People recommend plugins, frameworks, all that, just for the simple task of some basic params parsing.

To be frank, as I go on using Zend framework, I find it hard to believe the amount of effort people will put into searching for pre-made solutions for things that are really pretty simple. I suspect this has to do with the fact that "framework" is misinterpreted as "does everything for you", which leads a lot of what I call "script hackers" to pursue them, when in fact using frameworks is a more advanced programming undertaking that, imho, separates the men from the boys, as it were. I understand that situationally a lot of that might be useful, but for me, when it comes to basic operations such as this, I prefer to use the features of the language without additional bolt-on libs, mods, and what have you.

Here's the code I use, which has worked consistently well, in a little util class. If you have other character or encoding concerns, just bolt them into the processing before you hit the foreach loop.



public static function parseURIParams ( $uri )
{
$params = parse_url ( $uri, PHP_URL_QUERY );
$values = explode ( '&', $params );
$finalParamsArray = array ( );

foreach ( $values as $str )
{
$keyVal = explode ( '=', $str );
$finalParamsArray [ $keyVal [ 0 ] ] = $keyVal [ 1 ];
}

return $finalParamsArray;
}