Extract query string into an associative array with PHP
Posted November 2nd, 2009 in PHP
A little while back I posted how to extract the domain, path, etc from a url with PHP and in this follow up post show how to extract the query string into an associative array using the parse_str function.
Extract the query string with parse_url
In this example we'll look at the URL from querying [chris hope] at Google (I don't show up until the second page, by the way) which looks like this:
http://www.google.com/search?hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=
Using parse_url we can easily extract the query string like so:
$parts = parse_url($url); echo $parts['query'];
The output from the above will be this:
hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=
As an aside, before continuing with using parse_str to extract the individual parts of the query string, doing print_r($parts) would show this:
Array
(
[scheme] => http
[host] => www.google.com
[path] => /search
[query] => hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=
)
Extract the query string parts with parse_str
The parse_str function takes one or two parameters (the second from PHP 4.0.3) and does not return any values. If the second parameter is present, the values from the query string are returned in that parameter as an associative array. If it is not present, they are instead set as variables in the current scope, which is not really ideal.
So, without the first parameter:
parse_str($parts['query']);
You could now echo the "q" value like this:
echo $q;
In my opionion, it's better to have the values returned as an array like so:
parse_str($parts['query'], $query);
Now doing print_r($query) would output this:
Array
(
[hl] => en
[source] => hp
[q] => chris hope
[btnG] => Google Search
[meta] =>
[aq] => f
[oq] =>
)
The "q" value could now be echoed like this:
echo $query['q'];
Related posts:
- Extract domain, path etc from a full url with PHP (Monday, September 28th 2009)
- Extract images from a web page with PHP and the Simple HTML DOM Parser (Monday, September 14th 2009)
- Get meta tags from an HTML file with PHP (Thursday, September 10th 2009)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
