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?

2
  • 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. Commented Feb 6, 2017 at 18:30
  • how is this answer? stackoverflow.com/a/55160197/8058753 it can encode also path. Commented Mar 14, 2019 at 10:33

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.