Estrarre una query string dentro un array associativo con PHP

Posted on 14. Nov, 2009 by daniele in php, tutorials


In questo tutorial imparerete ad estrarre una query in un array associativo, per fare ciò utilizzeremo la funzione parse_url che si occuperà di "spezzettare" l'url e di poter ottenere quindi la query string!

 
< ?php
$url = "http://www.google.com/search?hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=";
$parts = parse_url($url);
echo $parts['query'];
 
//OUTPUT
//hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=
/*Array
(
    [scheme] => http
    [host] => www.google.com
    [path] => /search
    [query] => hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=
)*/
?>
 

Se volessimo a sua volta estrarre la query string restituita basterà fare:

 
< ?php
parse_str($parts['query'], $query);
//OUTPUT
/*Array
(
    [hl] => en
    [source] => hp
    [q] => chris hope
    [btnG] => Google Search
    [meta] =>
    [aq] => f
    [oq] =>
)*/
?>
 

Correlati

Leave a reply