20 Awesome PHP Libraries For Summer 2016

By Danny Markov


Initially released in 1995, the PHP language is now of legal drinking age, but this doesn’t stop it from still being one of the most popular languages out there, and the first choice of many back-end developers.

The PHP community on GitHub is also one of the biggest and most active, with new awesome projects coming out constantly. Here are our picks for the 20 most useful and interesting open-source PHP libraries that you should check out – 2016 edition!


With Monolog you can create advanced logging systems by sending your PHP logs to files, sockets, databases, inboxes or other web services. The library has over 50 handlers for various utilities and can be integrated into frameworks such as Laravel, Symfony2 and Slim.

use MonologLogger;
use MonologHandlerStreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log


A set of PHP classes that allow developers to easily implement spreadsheet editing in their apps. The library can read and write spreadsheet documents in a number of popular formats including Excel (both .xls and .xlsx), OpenDocument (.ods), and CSV to name a few.

include 'PHPExcel/IOFactory.php';

$inputFileName = './sampleData/example1.xls';

echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);


An interesting library for experimenting with Machine Learning, PHP-ML gives you an easy to use API for training your bot and making it do predictions based on input data. It offers a variety of different algorithms for pattern recognition and complex statistics calculations.

use PhpmlClassificationKNearestNeighbors;

$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];

$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

$classifier->predict([3, 2]);
// returns 'b' as the [3, 2] point is closer to the points in group b


Library for enabling users to authenticate themselves via their account in social networks or other services. Of course all the big names are available: Google, Facebook, Twitter, Github, Instagram, LinkedIn. Opauth is supported by many PHP frameworks so it can be easily integrated in most PHP apps.

'Strategy' => array(  
    // Define strategies here.

    'Facebook' => array(
        'app_id' => 'YOUR APP ID',
        'app_secret' => 'YOUR APP SECRET'


Whoops greatly improves the debugging experience in PHP by displaying a detailed error page when something breaks in an app. This error page gives us the full stack trace showing the specific files and snippets of code that caused the exception, all syntax-highlighted and colorful. The Laravel framework comes with Whoops built-in.

$whoops = new WhoopsRun;
$whoops->pushHandler(new WhoopsHandlerPrettyPageHandler);
// That's it!


Implementing this caching system in your PHP apps is guaranteed to make them load way quicker by reducing the amount of queries sent to the database. Instead of executing every DB query, FastCache sends only the unique ones, saves them as cache, and then serves them from there for each repetition. This way if you have the same query repeated 1000 times, it will be loaded from the DB one time, the rest 999 loads will be from cache.

use phpFastCacheCacheManager;

$config = array(
    "storage"   =>  "files",
    "path"      =>  "/your_cache_path/dir/",

// Try to get from Cache first with an Identity Keyword
$products = CacheManager::get("products");

// If not available get from DB and save in Cache.
if(is_null($products)) {
    $products = "DB SELECT QUERY";
    // Cache your $products for 600 seconds.
    CacheManager::set($cache_keyword, $products,600);


Guzzle is one of the best HTTP clients out there. It can handle almost any HTTP task that you throw at it: synchronous and asynchronous requests, HTTP cookies, streaming of large uploads and downloads. Working with Guzzle is really easy and the docs are well written with lots of examples and detailed explanations.

$client = new GuzzleHttpClient();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// Send an asynchronous request.
$request = new GuzzleHttpPsr7Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();


Munee has lots of tricks up its sleeve: combining several CSS or JavaScript requests into one, image resizing, automatic compilation for Sass, Less and CoffeeScript files, as well as minification and Gzip compression. All of the previously mentioned processes are cached both server-side and client-side for optimal performance.

require 'vendor/autoload.php';
echo MuneeDispatcher::run(new MuneeRequest());
<!-- Combining two CSS files into one. -->
<link rel="stylesheet" href="/css/bootstrap.min.css, /css/demo.css">

<!-- Resizing image -->
<img src="/path/to/image.jpg?resize=width[100]height[100]exact[true]">

<!-- Files that need preprocessing are compiled automatically -->
<link rel="stylesheet" href="/css/demo.scss">

<!-- Minifying code -->
<script src="/js/script.js?minify=true"></script>


Templating engine with a very clean “mustache” syntax that makes markup shorter and easier to write. Twig offers everything you would expect from a modern templating library: variable escaping, loops, if/else blocks, as well as a secure sandbox mode for verifying template code.

// Template HTML

<p>Welcome {{ name }}!</p>

// Rendering

require_once '/path/to/lib/Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
    'cache' => '/path/to/compilation_cache',

echo $twig->render('index.html', array('name' => 'George'));


Goutte is a Web Scraper that can crawl websites and extract HTML or XML data from them. It works by sending a request to a given URL and returning a Crawler object, which allows the developer to interact with the remote page in various ways.

use GoutteClient;
$client = new Client();

// Go to the symfony.com website
$crawler = $client->request('GET', 'http://www.symfony.com/blog/');

// Click on the links
$link = $crawler->selectLink('Security Advisories')->link();
$crawler = $client->click($link);

// Extract data
$crawler->filter('h2 > a')->each(function ($node) {
    print $node->text()."n";


Climate is a library for people who run PHP from the command line. It offers a collection of methods for talking to the terminal (both input and output), and also some beautifying functions for coloring and formatting. It can even draw and animate cool ASCII art.

$climate = new LeagueCLImateCLImate;

// Output
$climate->out('This prints to the terminal.');

// Input
$input = $climate->input('How you doin?');
$response = $input->prompt();

// Formatting
$padding = $climate->padding(10);

// Eggs...... $1.99
// Oatmeal... $4.99


Built on top of Faker, Alice is a library that generates fake data objects for testing. To use it you first have to define the structure of your objects and what data you want in them. Then with a simple function call Alice will transform this template into an actual object with random values.

// Template in person.yml file
        firstName: '<firstName()>'
        lastName: '<lastName()>'
        birthDate: '<date()>'
        email: '<email()>'

// Load dummy data into an object
$person = NelmioAliceFixtures::load('/person.yml', $objectManager);


The Ratchet library adds support for the WebSockets interface in apps with a PHP backend. WebSockets enable two-way communication between the server and client side in real time. For this to work in PHP, Ratchet has to start a separate PHP process that stays always running and asynchronously sends and receives messages.

class MyChat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;

    public function onOpen(ConnectionInterface $conn) {

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {

// Run the server application through the WebSocket protocol on port 8080
$app = new RatchetApp('localhost', 8080);
$app->route('/chat', new MyChat);


No PHP library collection is complete without PHPMailer. This project is backed by a huge community and is implemented in popular systems such as WordPress and Drupal, making it the safest choice for sending emails in PHP. It has SMTP support, can do HTML-based emails, and much more.

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->setFrom('from@example.com', 'Mailer');


$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';


Hoa isn’t actually a PHP library – it’s an entire set of PHP libraries, containing all kinds of useful web development utilities. Although not all are fully documented, there are 50+ libraries right now, with new ones constantly being added. It’s completely modular so you can select only the libraries you need without any clutter.

// Hoa Mail
$message            = new HoaMailMessage();
$message['From']    = 'Gordon Freeman <gordon@freeman.hf>';
$message['To']      = 'Alyx Vance <alyx@vance.hf>';
$message['Subject'] = 'Hoa is awesome!';
    new HoaMailContentText('Check this out: http://hoa-project.net/!')

// Hoa Session
$user = new HoaSessionSession('user');

if ($user->isEmpty()) {
    echo 'first time', "n";
    $user['foo'] = time();
} else {
    echo 'other times', "n";


Anyone who has tried creating HTML emails knows what a pain it is to inline all of the CSS rules. This small PHP Class does the whole job for you, saving you lots of time and nerves. Just write your styles in a regular .css file and the PHP library will use the selectors to assign them at the proper tags.

use TijsVerkoyenCssToInlineStylesCssToInlineStyles;

// create instance
$cssToInlineStyles = new CssToInlineStyles();

$html = file_get_contents(__DIR__ . '/examples/sumo/index.htm');
$css = file_get_contents(__DIR__ . '/examples/sumo/style.css');

// output
echo $cssToInlineStyles->convert(


Library for doing all kinds of string manipulations. It offers a ton of different methods for modifying text (reverse(), htmlEncode(), toAscii() etc.) or gather information about a string (isAlphanumeric(), getEncoding(), among others). A cool thing about Stringy is that it also works with special symbols like Greek or Nordic letters;

s('Camel-Case')->camelize(); // 'camelCase'

s('   Ο     συγγραφέας  ')->collapseWhitespace(); // 'Ο συγγραφέας'

s('foo & bar')->containsAll(['foo', 'bar']); // true

s('str contains foo')->containsAny(['foo', 'bar']); // true

s('fòôbàř')->endsWith('bàř', true); // true

s('fòôbàř')->getEncoding(); // 'UTF-8'

s('&amp;')->htmlDecode(); // '&'


Robo is a Gulp-like task runner, only for PHP. With it you can set up automations that improve your workflow and the time it takes to build a project after making changes. Robo can run tests, compile code from preprocessors, handle version control updates, and many other useful tasks.

// Doing a Git Commit with Robo
public function pharPublish()
    $this->_rename('robo.phar', 'robo-release.phar');
    return $this->collectionBuilder()
            ->commit('robo.phar published')
            ->push('origin', 'gh-pages')

PHP Humanizer

This library takes variables and transforms them into a more human-readable format using a set of methods. For example it can turn Roman numerals into numbers, truncate long strings, and calculate bytes to kB/MB/GB. Support for over 15 languages (the spoken kind, not programming ones).

use CoduoPHPHumanizerNumberHumanizer;

echo StringHumanizer::humanize('field_name'); // "Field Name"

echo NumberHumanizer::ordinalize(1); // "1st"
echo NumberHumanizer::ordinalize(23); // "23rd"

echo NumberHumanizer::toRoman(5); // "V"
echo NumberHumanizer::fromRoman("MMMCMXCIX"); // 3999

echo NumberHumanizer::binarySuffix(1024); // "1 kB"
echo NumberHumanizer::binarySuffix(1073741824 * 2); // "2 GB"


The last item on our list is this small library for extracting colors from images. It iterates all of the pixels in a given picture and returns a palette of the colors on it sorted by total area. Developers can then use this palette to get the most dominant colors and adapt the design according to them.

require 'vendor/autoload.php';

use LeagueColorExtractorColor;
use LeagueColorExtractorPalette;

$palette = Palette::fromFilename('./some/image.png');

$topFive = $palette->getMostUsedColors(5);
$colorCount = count($palette);
$blackCount = $palette->getColorCount(Color::fromHexToInt('#000000'));

Source:: Tutorialzine.com