PHP: Convert query string to an object and vice versa

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

Working with query strings is common in web development. In PHP, you may need to convert query strings to objects for better access and handleability, and vice versa for HTTP requests. This tutorial covers different ways to manage this conversion, encompassing both built-in functions and custom code implementations.

Parsing a Query String into an Object

To parse a query string into an object, PHP provides a convenient function parse_str(). Here’s a basic example:

$queryString = 'name=John&age=30&occupation=developer';
parse_str($queryString, $output);
print_r($output);

This will output:

Array(
    [name] => John
    [age] => 30
    [occupation] => developer
)

For a more object-like experience, you can cast the result to an object:

$object = (object) $output;
echo $object->name; // Outputs: John

Converting an Array/Object to Query String

On the other hand, if you have an associative array or an object that you wish to convert back to a query string, you’d use http_build_query():

$params = ['name' => 'Jane', 'age' => 25, 'occupation' => 'designer'];
$queryString = http_build_query($params);
echo $queryString; // Outputs: name=Jane&age=25&occupation=designer

If you’re dealing with an object, ensure it’s converted to an array first:

$object = new stdClass();
$object->name = 'Jane';
$object->age = 25;
$object->occupation = 'designer';
$array = get_object_vars($object);
$queryString = http_build_query($array);
echo $queryString;

Handling Nested Arrays and Objects

PHP also supports nested arrays and objects. When converting nested structures to a query string, PHP will use a square bracket syntax:

$params = [
    'name' => 'Jane',
    'preferences' => [
        'color' => 'blue',
        'food' => 'sushi'
    ]
];
$queryString = http_build_query($params);
echo $queryString;
// Outputs: name=Jane&preferences[color]=blue&preferences[food]=sushi

Parsing this back is a bit tricky as parse_str() does not automatically convert this to a multi-dimensional array. For complex parsing, custom functions may be needed.

Working with URLs

In real-world scenarios, you will deal with full URLs. The parse_url() function breaks a URL into its components, and you can then target the query string:

$url = 'http://example.com/?name=Jane&age=25';
$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $queryParams);
print_r($queryParams);

Advanced Usage and Custom Functions

For more complex scenarios where you may need to sanitize or transform data, building custom functions is the way to go. Here, developers can utilize loops, regex, and various PHP string and array functions to manage the conversion exactly as needed, potentially handling edge cases the built-in functions don’t cover.

Encoding and Decoding

Keep in mind the RFC 3986 standard when dealing with URI encoding and decoding. PHP’s urlencode() and urldecode() functions are crucial for proper encoding and handling of special characters in URL query strings.

Caching

If performance is a concern, especially when dealing with large query strings or complex conversions, caching the results could be an advantageous strategy. PHP offers various caching techniques, such as in-memory stores like APCu or memcached.

Conclusion

To convert query strings to objects and vice versa, PHP developers can rely both on built-in functions and custom implementations for complex cases. Understanding these conversions is essential for processing GET parameters, form submissions, and building dynamic URLs for web applications.