detectlanguage / detectlanguage-php

Detect Language API PHP Client
https://detectlanguage.com
MIT License
51 stars 12 forks source link

Throws an error with special characters in Laravel #7

Closed wpas81 closed 3 years ago

wpas81 commented 3 years ago

Hi

I've been a longtime (and happy!) user. I'm currently converting my site to Laravel and thus also my languagedetect routine. This however gives me an error:

DetectLanguage::detect("Buenos dias señor"); throws an error while DetectLanguage::detect("Buenos dias senor"); doesn't (same with é, à etc)

The error thrown is ` Invalid server response:

at vendor/detectlanguage/detectlanguage/lib/DetectLanguage/Client.php:45 41▕ $response_body = self::$request_method($url, $params); 42▕ $response = json_decode($response_body); 43▕ 44▕ if (!is_object($response)) ➜ 45▕ throw new Error("Invalid server response: $response_body"); 46▕ 47▕ if (isset($response->error)) 48▕ throw new Error($response->error->message); `

In Client.php the params-parameter is

array:1 [
  "q" => b"Buenos dias señor"
]

I'm guessing the 'b' doesn't belong there :) I can't seem to find where it's coming from?! it's already present in $text in the detect() class in DetectLanguage.php.

wpas81 commented 3 years ago

I fixed it:

/**

  • Detect text language.
  • @static
  • @param string @text The text for language detection
  • @return array detected languages information */ public static function detect(string $text) { $text = utf8_encode($text); $result = Client::request('detect', array('q' => $text));

    return $result->data->detections;

    }

laurynas commented 3 years ago

@wpas81 good to know you found a solution. Yes, text should be UTF-8.

wpas81 commented 3 years ago

Wouldn't it be better to perform a convert in the detect()-function?

laurynas commented 3 years ago

I don't think it is worth to doing conversion in the client, because it can result double-encoding.