Search code examples
phpapiencodinglinkedin-api

php urlencode for linkedin


Apparently Linkedin is funny about urlencoding the ~ in https://api.linkedin.com/v1/people/~ my problem is that i use an oauth library so I need to keep things consistent. is there a way to urlencode just part of the string so in case i have the ~ i can leave that out and put it back in at the same spot after encoding? thank you


Solution

  • Use rtrim() to remove ~ and then again append it:

    <?php
      $URL = 'https://api.linkedin.com/v1/people/~';
      echo urlencode( rtrim ( $URL, '~' ) ) . '~';
    ?>
    

    This outputs:

    https%3A%2F%2Fapi.linkedin.com%2Fv1%2Fpeople%2F~

    [EDIT]: After OP Clarification: If there are ~ in the middle somewhere

    Use str_replace to put back the character ~:

    <?php
       $URL = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name';
       echo str_replace('%7E','~',urlencode($URL));
    ?>
    

    This outputs:

    https%3A%2F%2Fapi.linkedin.com%2Fv1%2Fpeople%2F~%3A%28id%2Cfirst-name%2Clast-name