Par Nicolas SUPRIN, mardi 22 mai 2007 à 18:39 | PHP | #103 | rss
N'ayant pas trouvé de méthode pour analyser le contenu de la partie query (aprés le ?) d'une url, j'ai décidé d'écrire rapidement la méthode "http_parse_query".
http_parse_query (PHP 5)
http_parse_query — Analyse chaîne de requête en encodage URL
Description
string http_parse_query ( string S_query , string arg_separator )
http_parse_query() génère un tableau indexé ou associatif, construit à partir d'une chaîne en encodage URL. La chaîne de requêtes peut peut être un tableau monodimensionnelle simple, ou un tableau de tableaux (qui peuvent aussi contenir des tableaux).
Exemple 2608. Utilisation simple de http_parse_query()
<?php print_r(http_parse_query('foo=bar&baz=boom&cow=milk&php=hypertext+processor')); print_r(http_parse_query('foo=bar&baz=boom&cow=milk&php=hypertext+processo', '&')); ?>
Affichera
Array
(
[foo] => bar
[baz] => boom
[cow] => milk
[php] => hypertext processor
)
Array
(
[foo] => bar
[baz] => boom
[cow] => milk
[php] => hypertext processo
)
Exemple 2610. http_parse_query() avec tableau complexe
<?php print_r(http_parse_query('user[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%2F12%2F1956&pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap&children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8&children[sally][sex]=F&flags_0=CEO')); ?>
Affichera
Array
(
[user] => Array
(
[name] => Bob Smith
[age] => 47
[sex] => M
[dob] => 5/12/1956
)
[pastimes] => Array
(
[0] => golf
[1] => opera
[2] => poker
[3] => rap
)
[children] => Array
(
[bobby] => Array
(
[age] => 12
[sex] => M
)
[sally] => Array
(
[age] => 8
[sex] => F
)
)
[flags_0] => CEO
)
Le code source
function http_parse_query ($S_query, $S_arg_separator = '&') { $A_return = array(); // pour chaque attribut foreach (explode($S_arg_separator, $S_query) as $S_attribut) { // on en registre la cle et la valeur list($S_cle, $S_valeur) = explode('=', $S_attribut); preg_match_all('/([^\[|\]]+)/', $S_cle, $A_element); $A_return = array_merge_recursive($A_return, _findValue(array(), $A_element[0], $S_valeur)); } return $A_return; } function _findValue($A_input, $A_cle, $S_valeur) { $I_taille = sizeof($A_cle); $S_celf = array_shift($A_cle); if ($I_taille <= 1) { $A_input[$S_celf] = urldecode($S_valeur); } else { $A_input[$S_celf] = _findValue($A_input, $A_cle, $S_valeur); } return $A_input; }
Conclusion
Cette méthode répond et s'inspire de la fonction _findValue contenue dans le paquet HTML_QuickForm, et peut ainsi remplacer le fameux eval.






Aucun commentaire pour le moment.
Aucun trackback.
Les trackbacks pour ce billet sont fermés.
Les commentaires pour ce billet sont fermés.