Documentation for crwlr / query-string (v1.0)

String Output Settings

There are some things that can be handled differently in query strings, for example how space characters are encoded (+ vs. %20) or the separator character (&). Here are all the settings available with the Query class.

Space Character Encoding

By default PHP's http_build_query() function uses PHP_QUERY_RFC1738 which means it uses the + character, like: foo=bar+baz. The Query class uses the same default. If you want to change it to PHP_QUERY_RFC3986 (%20) you can do that like:

$query = Query::fromString('foo=bar baz')
    ->spaceCharacterEncoding(PHP_QUERY_RFC3986);

// string(13) "foo=bar%20baz"

As the constants might not be very memorable, there is also an alias method for this:

$query = Query::fromString('foo=bar baz')
    ->spaceCharacterPercentTwenty();

// string(13) "foo=bar%20baz"

If for some reason you have an instance that uses %20 and you want to change it back to use + use the spaceCharacterPlus() method:

$query->spaceCharacterPlus(); // Equivalent to $query->spaceCharacterEncoding(PHP_QUERY_RFC1738);

// string(11) "foo=bar+baz"

Changing the Separator Character

By default the Query() class uses the & character as separator, just like PHP's http_build_query(). But you can also use a different separator:

$query = Query::fromArray(['foo' => '1', 'bar' => '2', 'baz' => '3'])
    ->separator(';');

// string(17) "foo=1;bar=2;baz=3"

As PHP's parse_str() function sadly has no option to set a different separator, creating a Query instance from string with a custom separator doesn't work and throws an Exception. If you'd need this, let me know via twitter or github.

Boolean Value Representation

By default, boolean values are converted to 0 and 1 in query strings.

$query = Query::fromArray(['foo' => true, 'bar' => false]);

// string(11) "foo=1&bar=0"

If you want to you can let them be converted to strings true and false:

$query = Query::fromArray(['foo' => true, 'bar' => false])
    ->boolToString();

// string(18) "foo=true&bar=false"