PHP – Parse the GET, POST, and COOKIE data using mb_parse_str()

The mb_parse_str() function in PHP is used to parse URL-encoded data (commonly from GET, POST, and COOKIE) and converts it into an array. It automatically detects the encoding and converts it to the internal encoding, making it useful for handling multibyte character strings.

Syntax

bool mb_parse_str(string $encoded_string, array &$result)

Parameters

The mb_parse_str() function accepts the following parameters −

  • $encoded_string − The URL-encoded data string to be parsed.

  • $result − An array that will hold the parsed key-value pairs after decoding and character conversion.

Return Values

The function returns true on success or false on failure. The parsed data is stored in the second parameter as an associative array.

Example 1: Basic Usage

Here's how to parse a simple URL-encoded string −

<?php
   $str_string = "user_id=123&email=xyz@gmail.com&country=India";
   $array_result = array();

   // Parse the data
   $success = mb_parse_str($str_string, $array_result);
   
   if ($success) {
       print_r($array_result);
   } else {
       echo "Failed to parse string";
   }
?>
Array
(
    [user_id] => 123
    [email] => xyz@gmail.com
    [country] => India
)

Example 2: Handling Special Characters

The function properly handles URL-encoded special characters −

<?php
   $encoded_data = "name=John%20Doe&message=Hello%20World%21&symbol=%26";
   $result = array();

   mb_parse_str($encoded_data, $result);
   print_r($result);
?>
Array
(
    [name] => John Doe
    [message] => Hello World!
    [symbol] => &
)

Key Points

  • Automatically handles URL decoding (e.g., %20 becomes space)

  • Converts character encoding to internal encoding

  • Useful for processing form data or query strings

  • Returns boolean value indicating success/failure

Conclusion

The mb_parse_str() function is essential for parsing URL-encoded data while handling multibyte characters correctly. It provides a reliable way to convert query strings into associative arrays for further processing in PHP applications.

Updated on: 2026-03-15T10:00:37+05:30

698 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements