Is there any reliable alternative to parse_str()
function for parsing a query string?
I found it very confusing and error-prone specially when query string is coming from an external service (and you can't fully control it):
$error = "Error message";
parse_str("param1=hello&error=false"); // Overrides $error
parse_str($externalQuery);
// Which variables are setted and which not?
$error = "Error message";
$output_array = array();
parse_str("param1=hello&error=false", $output_array);
var_dump($output_array);
Do you really need to overwrite existing variables or to create new 'unknown' variables?
Pass the optional second argument to parse_str()
and it will place the values in an associative array instead of creating/overwriting variables. From the php manual:
If the second parameter arr is present, variables are stored in this variable as array elements instead.
You must initialize the array first. Do this:
$error = "Error message";
$vars = array();
parse_str("param1=hello&error=false", $vars);
echo $error . "
";
print_r($vars);
which outputs:
Error message
Array
(
[param1] => hello
[error] => false
)
Take another look at the docs. parse_str
supports passing a 2nd parameter which will store the variables.
$error = "Error message";
parse_str("param1=hello&error=false", $data);
echo $error; // "Error message"
var_dump($data['error']); //false
You can pass an array to parse_str
, and it will put the query string KV pairs in:
$error = "Error message";
$queryString = array();
parse_str("param1=hello&error=false", $queryString);
echo $error; //"Error message"
echo $queryString["error"]; //"false" (actually will echo "")
Use \GuzzleHttp\psr7\parse_query function, which is available with guzzlehttp/psr7 composer package.
That worked for me - parse_str simply failed to parse some queries and returned an empty array.
It has a more modern synrax:
$aParsedQuery = parse_query($sQueryString, $bUrlDecode);
Where the second parameter is true by default.