4.7.x common.inc drupal_query_string_encode($query, $exclude = array(), $parent = '')
5.x common.inc drupal_query_string_encode($query, $exclude = array(), $parent = '')
6.x common.inc drupal_query_string_encode($query, $exclude = array(), $parent = '')

Parse an array into a valid urlencoded query string.

Parameters

$query: The array to be processed e.g. $_GET.

$exclude: The array filled with keys to be excluded. Use parent[child] to exclude nested items.

$parent: Should not be passed, only used in recursive calls.

Return value

An urlencoded string which can be appended to/as the URL query string.

Related topics

4 calls to drupal_query_string_encode()
pager_get_querystring in includes/pager.inc
Compose a query string to append to pager requests.
tablesort_get_querystring in includes/tablesort.inc
Compose a query string to append to table sorting requests.
theme_pager_link in includes/pager.inc
Returns HTML for a link to a specific query result page.
url in includes/common.inc
Generates an internal or external URL.

File

includes/common.inc, line 238
Common functions that many Drupal modules will need to reference.

Code

function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
  $params = array();
  foreach ($query as $key => $value) {
    $key = rawurlencode($key);
    if ($parent) {
      $key = $parent . '[' . $key . ']';
    }
    if (in_array($key, $exclude)) {
      continue;
    }
    if (is_array($value)) {
      $params[] = drupal_query_string_encode($value, $exclude, $key);
    }
    else {
      $params[] = $key . '=' . rawurlencode($value);
    }
  }
  return implode('&', $params);
}

Comments

snufkin’s picture

In Drupal 7 you should use drupal_http_build_query().

progga’s picture

Drupal uses UTF-8 by default for storing strings. If such a string containing an accented character is then passed to drupal_query_string_encode(), it is encoded differently from the way it would be encoded with a single byte encoding. Here is an example:

  • UTF-8 encoded string "Bláth" becomes "Bl%C3%A1th" after coming out of drupal_query_string_encode()
  • Single byte encoded string "Bláth" becomes "Bl%E1th" after coming out of drupal_query_string_encode()

If we are passing our query string to a site that uses single byte encoding instead of UTF-8, then this will cause problem. The solution is to convert the UTF-8 encoded string to a single byte encoded string through PHP's builtin utf8_decode() before passing it to drupal_query_string_encode(). Example follows:

  $query = array(
    'foo' => 1,
    'bar' => 'Bláth',  // UTF-8 encoded string.
  );

  $query['bar'] = utf8_decode($query['bar']);  // Converts to single byte encoding.

  $query_string = drupal_query_string_encode($query);