Draco
Draco

Reputation: 262

encoding chinese characters for url in php

So I have a bunch of urls and some of them have chinese characters in them like this: http://www.abcdefg.com/ad2/zh/profile/2169358/1/冰绿茶/

However I need to process all of these urls and encode the urls with the chinese characters in them into something like this: http://www.abcdefg.com/ad2/zh/profile/2169358/1/%E4%BA%8C%E4%B8%8D%E4%BA%8C%E7%9A%84%E4%BA%8C/

So the chinese part must be encoded in php.

I tried using urlencode, rawurlencode but none worked.

Any help would be greatly appreciated!

Note: The encoded urls are meant to be stored not displayed by the browser so changing the header is not an option.

Upvotes: 3

Views: 3680

Answers (1)

uzyn
uzyn

Reputation: 6693

For this case, you may wish to use parse_url() to separate the URL components and only urlencode() the path and query components.

$url = 'http://www.abcdefg.com/ad2/zh/profile/2169358/1/冰绿茶/';
$parsed = parse_url($url);

print_r($parsed);

You would get

Array
(
    [scheme] => http
    [host] => www.abcdefg.com
    [path] => /ad2/zh/profile/2169358/1/冰绿茶
)

so, urlencode() path and query (if any).

Once those are URL-encoded, you will need to reassemble back so that scheme (http), host(www.abcdefg.com) remain unaffected.

If you still prefer to have / intact, explode() the path first before URLencoding it.

$pathComponents = explode('/', $parsed['path']);

$pathComponents = array_map('urlencode', $pathComponents);

// Assemble back $path
$path = implode('/', $pathComponents);

Upvotes: 2

Related Questions