简体   繁体   English

在PHP中获取查询字符串不起作用

[英]Get query string in PHP doesn't work

I am a php newbie, and I'm trying to follow suggestions for how to get the query string. 我是php新手,我正在尝试遵循有关如何获取查询字符串的建议。 I want the words searched on in a readable format. 我希望以可读格式搜索单词。

Now, the strings come from a database, where they have been previously collected using the request object's referer property in Asp.Net. 现在,字符串来自数据库,该字符串以前是使用Asp.Net中的请求对象的Referer属性收集的。 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. 它给了我一个查询字符串部分,但包括了“ q =”和所有内容,而不仅仅是查询字符串的文本。

So I tried the parse_str() function on this, which is supposed to be able to parse the query string itself: 因此,我对此尝试了parse_str()函数,该函数应该能够解析查询字符串本身:

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)? (0索引只是一个例子,我想如果我设法只找出文本部分的话,可以将其串联起来)?

It would seem that you are trying to parse a url from a string, not from the current request (as mentioned in comment) 似乎您正在尝试从字符串而不是当前请求中解析url(如注释中所述)

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文档上,有一个很棒的功能,正是您想要的功能,我已经在此处复制了它,因此可以在以后的参考中使用-所有功劳归于“ 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM