0

I have a URL with space characters that I want to properly encode when making an API call (in this case replace ' ' with '%20' so the space characters are treated properly.

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

Hoever when using the urlencode($url) function I get this obscure representation of the URL

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

That I eventually cannot resolve.

enter image description here........

Is there a URL-encode function in PHP that just replaces spaces and quotation marks instead of making abrupt changes to the whole string?

Jebathon
  • 4,310
  • 14
  • 57
  • 108
  • 4
    You don't want to encode the entire thing, just: `$url = 'https://www.someapi.com?param='.urlencode('this and that');`. You're not encoding a URL you are encoding data to be used in a URL. – AbraCadaver Feb 06 '17 at 18:30
  • how is this answer? https://stackoverflow.com/a/55160197/8058753 it can encode also path. – harufumi.abe Mar 14 '19 at 10:33

1 Answers1

0

You can parse request url and only encode query string "values".

$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);

Result:

https://www.someapi.com?param=this%2Band%2Bthat
Ahmet Erkan ÇELİK
  • 2,364
  • 1
  • 26
  • 28