Sling Academy
Home/PHP/PHP: Convert query string to an object and vice versa

PHP: Convert query string to an object and vice versa

Last updated: January 10, 2024

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.

Next Article: PHP: Convert a string into an object and vice versa

Previous Article: PHP: Remove all non-alphanumeric characters from a string

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array