How to detect the Text Encoding of a File in PHP

It’s time to forget everything you were thinking about how to approach text encoding detection, because you won’t need it. We are going to cruise right past all those suckers trying to code this out by hand, instead opting for an alternative method. Here’s how it works.

Open up the command line of composer and paste in this snippet here.

composer require cloudmersive/cloudmersive_document_convert_api_client

That will begin the installation of our API client, which we can then use to call this function here:

<?phprequire_once(__DIR__ . '/vendor/autoload.php');// Configure API key authorization: Apikey$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Apikey', 'Bearer');$apiInstance = new Swagger\Client\Api\EditTextApi(// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.// This is optional, `GuzzleHttp\Client` will be used as default.new GuzzleHttp\Client(),$config);$input_file = "/path/to/file"; // \SplFileObject | Input file to perform the operation on.try {$result = $apiInstance->editTextTextEncodingDetect($input_file);print_r($result);} catch (Exception $e) {echo 'Exception when calling EditTextApi->editTextTextEncodingDetect: ', $e->getMessage(), PHP_EOL;}?>

Ready to be blown away? You’re done. That’s right, this is now fully functional and you can just input any text files that you wanted information on. Now go take a break! You’ve earned it.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store