Ebooks

PHP Faker tutorial

PHP Faker tutorial shows how to generate fake data in PHP with Faker package. We use the fzaninotto/Faker package.

PHP Faker

Faker is a PHP library that generates fake data. Faka data is often used for testing or filling databases with some dummy data. Faker is heavily inspired by Perl's Data::Faker, and by Ruby's Faker.

PHP Faker setup

The package is installed with composer.

$ composer req fzaninotto/faker 

We install the fzaninotto/faker package.

$ composer req symfony/var-dumper

In addition, we install the Symfony Dumper, which provides nicer console output when dumping variables.

Faker factory

With Faker\Factory::create() we create and initialize a faker generator. On the generator, we access the generator properties (called formatters) to generate fake data. Internally, Faker delegates the data generation to providers.

The default provider uses the English locale. Faker supports other locales; they differ in level of completion.

Simple Faker example

The following example is a simple demonstration of Faker.

simple.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

echo $faker->name . "\n";
echo $faker->address . "\n";

The example outputs a fake name and address.

$ php simple.php
Antonia Hahn
355 Mills Light Apt. 722
Krajcikburgh, RI 36330

This is a sample output.

Faking names

In the second example, we fake data related to user names.

names.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

echo $faker->name() . "\n";
echo $faker->name('male') . "\n";
echo $faker->name('female') . "\n";

echo $faker->firstName() . "\n";
echo $faker->firstName($gender='male') . "\n";
echo $faker->firstName($gender='female') . "\n";

echo $faker->firstNameMale('female') . "\n";
echo $faker->firstNameFemale('female') . "\n";

echo $faker->lastName() . "\n";

The example creates fake full names, first names, last names of males and females.

$ php names.php
Darion Walker
Prof. Chet Kessler
Prof. Jaida Greenholt PhD
Cristopher
Reid
Gilda
Wiley
Juanita
Jones

This is a sample output.

Faking locale data

The Faker supports localized data to some extent. The locale is passed to the factory create() method. Note that the locales are finished to various levels.

localized.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create('sk_SK');

for ($i = 0; $i < 3; $i++) {

    $name = $faker->name;
    $city = $faker->cityName;
    $phone = $faker->phoneNumber;

    echo "$name, $city, $phone\n";
}

The example generates fake data in Slovak language.

$ php localized.php
RNDr. Kvetoslava Zelenayová DSc., Malé Dvorníky, 00421 742 587 664
Agáta Molnárová, Čabalovce, +421 857 627 309
PhDr. Igor Truben, Mokrá Lúka, 00421577302978

This is a sample output. Notice that Slovak language has accents.

Faking titles

The following example creates fake data for titles. Faker generates academic and personal titles.

titles.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

echo $faker->title() . "\n";
echo $faker->title('male'). "\n";
echo $faker->title('female'). "\n";

echo $faker->titleMale . "\n";
echo $faker->titleFemale . "\n"; 
echo $faker->suffix . "\n"; 

The program generates fake titles for males and females.

$ php titles.php
Ms.
Dr.
Miss
Prof.
Mrs.
DDS

This is a sample output.

Faking colours

Faker can create colour names or different colour formats, such as hexadecimal and RGB.

colours.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

echo $faker->hexcolor . "\n";
echo $faker->rgbcolor . "\n";
dump($faker->rgbColorAsArray);
echo $faker->rgbCssColor . "\n";
echo $faker->safeColorName . "\n";
echo $faker->colorName . "\n";

The example shows how to create colours with Faker.

$ php colours.php
#662d69
180,149,135
array:3 [
  0 => 190
  1 => 115
  2 => 170
]
rgb(119,164,223)
aqua
LightGreen
DarkGray

This is a sample output.

Faking numbers

The Faker allows to generate random digits, integers, or floating point values.

numbers.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

echo $faker->randomDigit . "\n";
echo $faker->randomDigitNotNull . "\n"; 

echo $faker->randomNumber() . "\n";
echo $faker->randomNumber($nbDigits = 3, $strict = true) . "\n";

echo $faker->randomFloat() . "\n";
echo $faker->randomFloat($nbMaxDecimals = 5, $min = 0, $max = 20) . "\n";
echo $faker->numberBetween($min = 1500, $max = 6000) . "\n";

dump($faker->shuffle([1, 2, 3, 4, 5, 6]));

The example generates random digits, integers, and floats. It also randomly shuffles array values.

$ php numbers.php
6
6
3654715
614
4164
12.29093
2347
array:6 [
  0 => 3
  1 => 6
  2 => 2
  3 => 5
  4 => 1
  5 => 4
]

This is a sample output.

Faking unique values

With unique() modifier, we can produce unique fake values.

unique_values.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

$vals = [];

for ($i = 0; $i < 6; $i++) {
    
  $vals[] = $faker->unique()->randomDigit;
}

dump($vals); 

The example generates an array containing six unique digits.

$ php unique_values.php
array:6 [
  0 => 0
  1 => 6
  2 => 9
  3 => 1
  4 => 5
  5 => 3
]

This is a sample output.

Faking optional values

With optional() modifier, we can produce optional fake values. Optional values can be null.

optional_values.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

$vals = [];

for ($i = 0; $i < 6; $i++) {
    
  $vals[] = $faker->unique()->randomDigit;
}

dump($vals); 

The example generates an array containing six optional digits.

$ php optional_values.php
array:6 [
  0 => 7
  1 => 4
  2 => null
  3 => null
  4 => null
  5 => 8
]

This is a sample output.

Faking internet related data

Faker has several accessors for faking internet related data.

internet.php
<?php

require('vendor/autoload.php');

$faker = Faker\Factory::create();

echo $faker->email . "\n";
echo $faker->safeEmail . "\n";
echo $faker->freeEmail . "\n";
echo $faker->companyEmail . "\n";
echo $faker->freeEmailDomain . "\n";
echo $faker->safeEmailDomain . "\n";
echo $faker->userName . "\n";
echo $faker->password . "\n";
echo $faker->domainName . "\n";
echo $faker->domainWord . "\n";
echo $faker->tld . "\n";
echo $faker->url . "\n";
echo $faker->slug . "\n";
echo $faker->ipv4 . "\n";
echo $faker->localIpv4 . "\n";
echo $faker->ipv6 . "\n";
echo $faker->macAddress . "\n";

The example shows various internet related data, including emails, domain names, slugs, IP addresses and URLs.

$ php internet.php
johns.ryleigh@rowe.com
merle96@example.com
nyasia.bergnaum@hotmail.com
morar.dylan@champlin.com
gmail.com
example.net
bartoletti.ena
}#)W+OVU<Lgaa.Atp5^
metz.com
blanda
org
http://www.kling.com/
optio-magnam-provident-pariatur-dolores-consequatur-beatae
127.131.186.145
10.135.68.26
ccf1:64a7:d145:98eb:742d:dc60:cf9e:5d4a
C8:31:FD:24:15:06

This is a sample output.

Generating XML data with Faker

In the following example, we generate XML data with Faker and Twig template. The XML file will contain users.

$ mkdir fakexml
$ cd fakexml
$ mkdir templates
$ composer req fzaninotto/faker
$ composer req twig/twig

We create a new project directory and install Faker and Twig template engine.

User.php
<?php

class User
{
    public $firstName;
    public $lastName;
    public $occupation;

    function __construct(string $first, string $last, string $occupation) 
    {
        $this->firstName = $first;
        $this->lastName = $last;
        $this->occupation = $occupation;
    }
}

This is the User.php, which has the following attributes: $firstName, $lastName, and $occupation;

fake_xml.php
<?php

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/User.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Faker\Factory;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$faker = Factory::create();

$users = [];

for ($i = 0; $i < 20; $i++) 
{
    $firstName = $faker->firstName;
    $lastName = $faker->lastName;
    $occupation = $faker->jobTitle;

    $user = new User($firstName, $lastName, $occupation);
    array_push($users, $user);
}

$content = $twig->render('users.xml.twig', ['users' => $users]);
file_put_contents('users.xml', $content);

The program generates an array of twenty users. The array is passed to the Twig template to be processed. The template is located in the templates directory. The generated content is written to the users.xml file.

templates/users.xml.twig
<?xml version="1.0" encoding="UTF-8"?>
<users>
    {% for user in users %}
    <user id="{{ loop.index }}">
        <firstname>{{ user.firstName }}</firstname>
        <lastname>{{ user.lastName }}</lastname>
        <occupation>{{ user.occupation }}</occupation>
    </user>
    {% endfor %}
</users>

In the template, we use the for directive to process the array of users.

In this tutorial, we have used PHP Faker to generate fake data in PHP.

You might also be interested in the following related tutorials: PHP PDO tutorial, Twig tutorial, and PHP tutorial.