Learn how to create your own translator in your Symfony project.

How to translate text in different languages using Google Translate for free in Symfony 3

Important

This tutorial doesn't use the paid Google Translate API, instead it uses the free alternative that crawls the Google Translate website.

This package is developed for educational purposes only and it comes in handy for personal usage (your own crazy projects). Do not depend on this package as it may break anytime as it is based on crawling the Google Translate website. Consider buying Official Google Translate API for other types of usage. Also, Google might ban your server IP or require to solve CAPTCHA if you send unusual traffic (large amount of data/requests).

Nowadays many people relies heavily on machine translation, specially on Google Translate. The translation of Google is remarkably good, at least if you compare it with the translation that other services generate. However, everybody knows that Google Translate is by no means a perfect translation service but very acceptable.

If you're looking to create some kind of personal translation module or service for your personal application that doesn't cost money (not the translation of items in your user interface), then you have landed in the right website. In this article you will learn how to translate text with PHP using the Google Translate PHP package in your Symfony project.

1. Install the Google Translate PHP package

In order to translate text to all the languages that the Google website allows, we'll use the Google Translate PHP package. It's an useful API that allows you to use the Google Translate functionalities for free (translates totally free of charge). 

To install this package in your symfony project, run the following command in your terminal (once located in your project directory):

composer require stichoza/google-translate-php

If you don't like to install packages with the console (or you like to use specific versions), you can edit manually your composer.json and add the package as a dependency:

{
    "require": {
        "stichoza/google-translate-php": "~3.2"
    }
}

Then run composer install and you're ready to use the package. This package relies on the Guzzle HTTP package and it was written by @Stichoza.  If you need more information about this package, please visit the official repository in Github here.

2. Translating text

The translation of text with this package is pretty easy, you only need to import the TranslateClient class from the package and create a new instance of it. It's important that you set the language of the text that you want to translate with the respective code (source language) with setSource and to set the output language (translated text) with setTarget.

Then you can use the translate method from the instance, this method expects as first argument the text that you want to translate:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Import the TranslateClient class
 */
use Stichoza\GoogleTranslate\TranslateClient;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // By default the TranslateClient is from 'auto' to 'en'
        $tr = new TranslateClient();

        $tr->setSource('en'); // Translate from English
        $tr->setTarget('es'); // Translate to Spanish

        $text = $tr->translate('Hello World!');

        // Outputs "Hola Mundo!"
        return new Response($text);
    }
}

You can see the list of codes of all the available languages of Google Translate here.

Using a static method

You don't need to create an instance of the TranslateClient as it exposes a static method to make the things easier and straightforward:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Import the TranslateClient class
 */
use Stichoza\GoogleTranslate\TranslateClient;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $sourceLanguage = "es";
        $outputLanguage = "pt";

        $textToTranslate = "buenos días";
 
        $text = TranslateClient::translate($sourceLanguage, $outputLanguage, $textToTranslate);

        // Outputs "bom Dia"
        return new Response($text);
    }
}

Detect source language automatically

In the same way that the translate app of Google does, you can set the automatic language recognition by setting the source language to null:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Import the TranslateClient class
 */
use Stichoza\GoogleTranslate\TranslateClient;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // By default the TranslateClient is from 'auto' to 'en'
        $tr = new TranslateClient();

        $tr->setSource(null); // Detect automatically the language
        $tr->setTarget('en'); // Translate to Spanish

        // It should detect german
        $text = $tr->translate('Guten Morgen');

        // Outputs "Detected language 'de' and translation: Good Morning"
        return new Response("Detected language code '{$tr->getLastDetectedSource()}' and translation: $text");
    }
}

As you can see, you can retrieve the detected language code with the getLastDetectedSource method of the client.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors