1

我想在 http_build_query (PHP) 的帮助下从数组中创建一个 url。这是数组:

$a = array("skip" => 1, "limit" => 1, "startkey" => '["naturalProduct","Apple"]')

打电话后

$s = http_build_query($a);

我得到以下字符串 $s:

skip=1&limit=1&startkey=%5B%22naturalProduct%22%2C%22Apple%22%5D

我的问题是,我需要这样的网址:

skip=1&limit=1&startkey=["naturalProduct","Apple"]

这意味着,我不想转换以下符号:",[]

我编写了一个在 http_build_query 之后调用的转换函数:

str_replace(array("%5B", "%22", "%5D", "%2C"), array('[', '"', ']', ','), $uri);

我现在的问题是:有没有更好的方法来达到预期的结果?

4

2 回答 2

6

我现在的问题是:有没有更好的方法来达到预期的结果?

是的,有更好的东西。http_build_query默认情况下, Docs使用 RFC 1738 中概述的 URL 编码。您只想对字符串进行反 URL 编码。为此,有一个功能可以在您的情况下执行此操作:urldecodeDocs

$s = http_build_query($a);
echo urldecode($s);

我希望您知道,在您完成此操作后,您的 URL 将不再是有效的 URL。你已经解码了。

于 2012-06-10T10:19:33.583 回答
1

您不需要解码特殊字符 - 它们会在 PHP 的$_GET超全局生成时自动解码。当我print_r($_GET)处理你生成的字符串时,我得到了这个:

数组 ( [skip] => 1 [limit] => 1 [startkey] => [\"naturalProduct\",\"Apple\"] )

它已经解码了每个字符,但没有取消双引号。要取消转义,请使用stripslashes()

echo stripslashes($_GET['startkey']);

这给

[“自然产品”,“苹果”]

然后您可以根据需要解析或使用它。正如 ThiefMaster 在评论中提到的,一个更好的解决方案是magic_quotes_gpc在你的php.ini; 它已被弃用并计划在 PHP6 中完全删除。

于 2012-06-10T10:13:27.560 回答