开发者

Get query string in PHP doesn't work

开发者 https://www.devze.com 2023-04-09 05:01 出处:网络
I am a php newbie, and I\'m trying to follow suggestions for how to get the query string. I want the words searched on in a readable format.

I am a php newbie, and I'm trying to follow suggestions for how to get the query string. I want the words searched on in a readable format.

Now, the strings come from a database, where they have been previously collect开发者_StackOverflow中文版ed using the request object's referer property in Asp.Net. But as far as I know that shouldn't make any difference.

So I tried this:

function getQuery($url)
{
        $processed_url = parse_url( $url );

        $query_string = $processed_url['query'];
        if($url != '')
        {
            return $query_string;
        }
        else
        {
            return $url;
        }
}

So I tried a variation, which should also extract the query string:

    $query = parse_url($url, 6);

    return $query;

Well, that sort of works. It gives me a query string part, but including the "q=" and all that, not just the text of the query string.

So I tried the parse_str() function on this, which is supposed to be able to parse the query string itself:

parse_str($query, $myArray);
return $myArray[0];

But that didn't work at all, it gives me no results in the result page (a grid).

What am I doing wrong? First of all with the first method for getting the query above, and secondly for parsing the query string into its components? (the 0 index was just an example, I thought I'd concatenate it later if I managed to get out only the text parts)?


It would seem that you are trying to parse a url from a string, not from the current request (as mentioned in comment)

On the PHP docs in the comments, there is a great function, that does exactly what you want, i have copied it here, so it can be used in future references - all credit goes to "Simon D" - http://dk.php.net/manual/en/function.parse-url.php#104527

<?php 
/** 
 * Returns the url query as associative array 
 * 
 * @param    string    query 
 * @return    array    params 
 */ 
function convertUrlQuery($query) { 
    $queryParts = explode('&', $query); 

    $params = array(); 
    foreach ($queryParts as $param) { 
        $item = explode('=', $param); 
        $params[$item[0]] = $item[1]; 
    } 

    return $params; 
} 
?>

which means it should be used like this:

$array = convertUrlQuery(parse_url($url, 6));
0

精彩评论

暂无评论...
验证码 换一张
取 消