Magento2 – How to Set Locale Programmatically

languagemagento2

i am create one test php file in magento root directory.
i install ar_SA Language pack and try to convert one string English to Saudi Arabia here is my test code.

<?php

ini_set('display_errors', 1);
ini_set('max_execution_time', 0);
ini_set("memory_limit", "-1");
set_time_limit(0);
error_reporting(E_ALL);
require './app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$localeInterface = $objectManager->create('Magento\Framework\TranslateInterface');
$localeInterface->setLocale('ar_SA');
echo $localeInterface->getLocale(); // it's print ar_SA

echo __('Check Value');

I have the corresponding translation in /i18n/ar_SA.csv file, it doesn't print the translated sentence.

Best Answer

Please try using Resolver Interface.

$localeInterface = $objectManager->create('Magento\Framework\Locale\ResolverInterface');

$localeInterface->setLocale('ar_SA');
$localeInterface->setDefaultLocale('ar_SA');

echo __('Check Value');

This is working in my case. if you have any query ask me.

Related Topic