3

I am trying to send an http request from my server to another server in php. The url that I send the request to contains some utf8 characters for example http://www.aparat.com/etc/api/videoBySearch/text/نوروز .

Here is my code:

 const api_adress = 'http://www.aparat.com/etc/api/';
 const xml_config = 'http://www.aparat.com/video/video/config/videohash/[ID]/watchtype/site';

 public function getDataInArray($JSON_ADRESS)
 {
     $json = json_decode(file_get_contents(self::api_adress . utf8_encode($JSON_ADRESS)), true);
     return ($json != NULL) ? $json : die(NULL);
}

I have also tried php-curl insted of file-get-contents but I got no answer.

Will
  • 24,082
  • 14
  • 97
  • 108
Alireza
  • 215
  • 1
  • 3
  • 13
  • Possible duplicate of [file\_get\_contents() Breaks Up UTF-8 Characters](http://stackoverflow.com/questions/2236668/file-get-contents-breaks-up-utf-8-characters) – ksno Jun 01 '16 at 07:30
  • No, it's not a duplicate. – Will Jun 01 '16 at 07:50
  • I see you've tried [utf8_encode()](http://php.net/). That function converts from ISO-8859-1 to UTF-8 and you cannot store Arabic characters in ISO-8859-1. – Álvaro González Jun 06 '16 at 14:38

1 Answers1

1

You just need to urlencode() the UTF-8 characters, like this:

php > $api = 'http://www.aparat.com/etc/api/';
php > $searchEndpoint = 'videoBySearch/text/';

php > var_dump($api . $searchEndpoint . urlencode('نوروز'));
string(79) "http://www.aparat.com/etc/api/videoBySearch/text/%D9%86%D9%88%D8%B1%D9%88%D8%B2"

php > $encodedUrl = $api . $searchEndpoint . urlencode('نوروز');
php > var_dump($encodedUrl);

string(79) "http://www.aparat.com/etc/api/videoBySearch/text/%D9%86%D9%88%D8%B1%D9%88%D8%B2"
php > var_dump(json_decode(file_get_contents($encodedUrl)));
object(stdClass)#1 (2) {
  ["videobysearch"]=>
  array(20) {
    [0]=>
    object(stdClass)#2 (17) {
      ["id"]=>
      string(7) "4126322"
      ["title"]=>
      string(35) "استقبال از نوروز 1395"
      ["username"]=>
      string(6) "tabaar"
      ...
    }
    ...
Will
  • 24,082
  • 14
  • 97
  • 108