【问题标题】:PHP urlencode not working as intendedPHP urlencode 未按预期工作
【发布时间】:2017-02-06 18:26:06
【问题描述】:

我有一个带有空格字符的 URL,我想在进行 API 调用时对其进行正确编码(在这种情况下,将“”替换为“%20”,以便正确处理空格字符。

$url = 'https://www.someapi.com?param=this and that';

但是,当使用 urlencode($url) 函数时,我会得到这个 URL 的模糊表示

"https%3A%2F%2..."

我最终无法解决。

........

PHP 中是否有一个 URL 编码函数,它只是替换空格和引号,而不是对整个字符串进行突然更改?

【问题讨论】:

  • 您不想对整个内容进行编码,只需:$url = 'https://www.someapi.com?param='.urlencode('this and that');。您没有对 URL 进行编码,而是对要在 URL 中使用的数据进行编码。
  • 这个答案怎么样? stackoverflow.com/a/55160197/8058753 也可以编码路径。

标签: php urlencode


【解决方案1】:

您可以解析请求 url,并且只对查询字符串“值”进行编码。

$url = "https://www.someapi.com?param=this and that";
$baseUrl = explode("?",$url)[0];
parse_str(parse_url($url,PHP_URL_QUERY),$args);
foreach ($args as $key=>&$arg){
    $arg= urlencode($arg);
} 
echo  $baseUrl."?".http_build_query($args);

结果:

https://www.someapi.com?param=this%2Band%2Bthat

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 1970-01-01
    • 2013-10-12
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 2018-12-22
    相关资源
    最近更新 更多