Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In PHP, I need a function to convert a querystring from an URL, say: http://example.com?key1=value1&key2=value2 into a PHP associative array : array ['key1' => 'value1', 'key2' => 'value2'].

I've come up to this piece of code. It works, but I find it a bit lengthy. (And PHP has built-in functions for everything: I'm surprised I haven't found anything out-of-the-box, something like the reverse of http_build_query.)

Can you suggest a better way to do this?

function getUrlParams($url) {
  $querystring = parse_url($url, PHP_URL_QUERY);
  $a = explode("&", $querystring);
  if (!(count($a) == 1 && $a[0] == "")) {
    foreach ($a as $key => $value) {
      $b = explode("=", $value);
      $a[$b[0]] = $b[1];
      unset ($a[$key]);
    }
    return $a;
  } else {
    return false;
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can get just the atributes from a URL using parse_url()

Once you have that you can use parse_str() to convert them to variables, it works with multidimensional arrays too!

$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...