Convert or Parse URL into PHP Associative Array

Nov 26, 2013, by admin

Here in this post, we’ll discuss how to convert or parse a URL into PHP associative array containing any of the various components of the URL that are present. For accomplishing this, we’ll use PHP build in function parse_url.

Parse an URL query string into PHP array

First let us take a look at the following URL query string:

  1. <?php
  2. $query_string =
  3. “http://phpzag.com?apikey=xg6tr7k&user=abcd&email=jhon.php%40example.com”;
  4. ?>

Now let’s take a look at how we can parse above URL query string into PHP array using PHP built in function parse_url:

  1. <?php
  2. $parsed_url = parse_url($query_string);
  3. print_r($parsed_url);
  4. ?>

Result array:

  1. Array (
  2. ‘scheme’ => ‘http’,
  3. ‘host’ => phpzag.com,
  4. ‘query’ => apikey=xg6tr7k&user=abcd&email=jhon.php%40example.com
  5. )