Make php project translation ready with gettext

I was working on php script that requires translation in multi-language, So I found two ways to make it translation ready with PO and MO files. Here are the two methods to translate a php project using gettext PO/MO files.

  1. PHP core Gettext library
  2. PHP Gettext class (Mainly written for wordpress)

PHP core Gettext requires GNU gettext package to be installed on system. Whereas PHP gettext class doesn’t have any dependency. It can directly ready MO file and extract translation text from that. Also It works on windows server without problem. So in this article I will guide you how to use php-gettext class.

How to Use?

First download php-gettext and use following code to make your php project translation ready.

Save following code as l10n.php

<?php
include('gettext.php');
include('streams.php');
function load_textdomain($mofile) {
global $l10n;
if ( is_readable($mofile))
$input = new CachedFileReader($mofile);
else
return;
$l10n = new gettext_reader($input);
}

function __($text){
global $l10n;
if (isset($l10n))
return $l10n->translate($text);
else
return $text;
}

function _n($single, $plural, $number){
global $l10n;
if (isset($l10n)) {
return $l10n->ngettext($single, $plural, $number);
}
else
{
if ($number != 1)
return $plural;
else
return $single;
}
}

?>

Uses

<?php
include('l10n.php'); //include above file
load_textdomain('en_US.mo'); //your mo file created with poedit
echo __('Hello World');
echo "\n";
echo sprintf( _n( '%s star', '%s stars', 1), 1 ); //testing singular
echo "\n";
echo sprintf( _n( '%s star', '%s stars', 10), 10 ); //testing plural 
?>

Now create PO/MO file using poedit just like WordPress.

Published by Sunny

A Mechanical engineer by education and web developer by passion and profession. He lives in Lucknow, India. Currently earning his livings by hitting keyboad. ;)

Leave a comment

Your email address will not be published. Required fields are marked *