How to extract attributes from an HTML string in PHP (without using RegEx)

Say you have an <a>, <link> or other HTML element and you need to extract its href (or other) attribute. You can extract those values using DOMDocument quite easily:

$custom_font = '<link href=";700&display=swap" rel="stylesheet">';

$link = $custom_font;
$dom = new DOMDocument();
foreach ($dom->getElementsByTagName("link") as $a) {
    echo $a->getAttribute("href");

How to iterate a list in batches using Twig (or plain PHP)

Recently I had to loop through a series of elements in a WordPress template (thanks Timber), which happened to be using Bootstrap.

If you ever used Bootstrap, you are familiar with the following markup:

<div class="row">
  <div class="element col-xs-4">
  <div class="element col-xs-4">
  <div class="element col-xs-4">
<div class="row">

The problem here is very common. You have to:

  • Loop every 3/4/n items.
  • Insert a separator or whatever every 3/4/n items.
Continue reading →

Build a simple website with Silex

Update: Silex has been deprecated in June 2018 in favor of Symfony.

I love static* websites. They’re usually faster to develop, smaller, require no database or backend and are faster to load. Of course they require more work to maintain and tweak at first, but if you’re a developer, these things should be pretty entertaining or at the very least, straightforward.

There are many options out there for building static websites; both free, like Anchor, Sculpin and Stacey; and paid, like Kirby and Statamic, among many others, like Silex.

This is a good moment to tell you that I’m aware of the difference of static websites vs flat-file CMSs vs micro-frameworks.

While I love the infinite possibilities of full-fledged CMSs and the blazing speed and simplicity of full-static websites, I feel that on most cases a good middle point is useful. That’s why I frequently choose micro-frameworks (or flat-file CMSs) over full CMSs or static site generators. One gives too many options, the other is too restrictive.

Silex is “a PHP micro-framework built on the shoulders of Symfony2 and Pimple and also inspired by Sinatra.”

It’s really simple to put together a simple website running Silex.

First, run composer init to start your project.

Then add silex/silex and twig-bridge, to use the Twig templating engine:

    "require": {
        "silex/silex": "^1.2",
        "symfony/twig-bridge": "^2.6"

Then just run composer install on a Terminal.

After that, all your dependencies should be sitting in your /vendor’s app directory.

Create an index.php file with this contents:

require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

// $app['debug'] = true;

$app->register(new Silex\Provider\UrlGeneratorServiceProvider());

// Register Twig provider and define a path for twig templates
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/views',

// Home page
$app->get('/', function() use($app) {
    return $app['twig']->render('index.html');

// Other page
$app->get('/other', function() use($app) {
    return $app['twig']->render('other.html');

// 404 - Page not found
$app->error(function (\Exception $e, $code) use ($app) {
    switch ($code) {
        case 404:
          return $app['twig']->render('404.html');
            $message = 'The requested page could not be found.';
            $message = 'We are sorry, but something went terribly wrong.';

    return new Response($message);


This bootstraps Silex. Here I declared two routes: / (home) and /other, which load the views index.html and other.html respectivly, on the /views folder.

That’s it! Following the same pattern, you can define as many pages as you wish.

If you need to do more complicated stuff like sending e-mails, do some logging or build forms, you can check the Silex documentation.


Laravel Homestead: multiple projects, one VM

Vagrant is great to isolate a development environment inside a VM. However, after a while you can find you have a bunch of heavy VMs that share the same characteristics, each one for a simple PHP project.

Enter Laravel Homestead

In these cases, you can safely use Laravel Homestead. Homestead is a Vagrant box pre-configured with an Nginx web server, PHP 5.6, MySQL, Postgres, Redis, Memcached, and other stuff to make development easier and faster.

The documentation is pretty clear and in a few steps you can have a working development environment, where you can add multiple projects.

Chek it out: Laravel Homestead

Update: Also, I recently found a simple guide on how to install MailCatcher on Homestead, which is really useful: Installing MailCatcher in Laravel Homestead

Run a simple HTTP server with one command line

Recently someone told me this great and simple trick on how to run an HTTP web server with just one command line. This is useful for a million things, but I use it for prototyping and avoid same-origin policy in Chrome. Sure, I know there’s a way to disable it, but you may not want to do that.

XMLHttpRequest cannot load file:///C:/Projects/Test/app/views/shell.html. Cross origin requests are only supported for HTTP.

This is all it takes:

$ cd /projects/TestProject
$ python -m SimpleHTTPServer 1234

Then you can access your files at localhost:1234.

I think this provides a much real environment while you build your HTML/JS. That way, you can have a more accurate preview on how your UI is going to feel when served through the Internet by a real server.

Note: This can also be achieved using PHP and probably a gazillion other programming languages.

Doctrine 2

Últimamente estuve trabajando bastante con CodeIgniter en conjunto con el ORM de Doctrine 1.2 para simplificar el acceso a datos y dar más poder que el Active Record que implementa el framework.

Hoy me topé con una presentación muy interesante de lo que traerá la versión 2, que aprovecha todo el potencial de PHP 5.3.

Una de las cosas más novedosas es el uso de namespaces y “annotations” para declarar una clase como entidad, sin tener que extender de una clase base:


namespace Entities; 

/** * @Entity @Table(name="users") */
class User {

	/** @Id @Column(type="integer") @GeneratedValue */
	private $id; 

	/** @Column(length=50) */
	private $name; 

	/** @OneToOne(targetEntity="Address") */
	private $address; 


Más información

Nace CodeIgniter Reactor

CodeIgniter LogoEllisLab, Inc., la empresa responsable y creadora de el framework PHP CodeIgniter anunció que a partir de el año que viene el desarrollo del mismo se dividirá en dos ramas:

CodeIgniter Core será mantenida por la empresa e incorporará cambios de la segunda rama, a un ritmo más lento, para adaptarse al ambiente empresarial.

CodeIgniter Reactor será la rama mantenida por la comunidad, guiada por seis ingenieros voluntarios y apadrinada por EllisLab. Esta rama tendrá un desarrollo más dinámico.

Eventualmente los cambios implementados en Reactor se implementarían en Core, una vez que estén suficientemente probados y sean aceptados por la empresa.

Para comenzar a contribuír con el proyecto, basta con entrar al espacio de CodeIgniter Reactor que crearon sobre la plataforma de UserVoice y comenzar a darle peso a las funcionalidades que creemos que hacen falta: CodeIgniter Reactor (UserVoice).

Más información


Friendly URLs in XAMPP

Update: this post is pretty old. I recommend you give Local a try.

A very common requirement for today’s apps is having “friendly” or clean URLs. We can achieve that easily in XAMPP, following these steps:

First, enable Apache’s mod_rewrite module:

Edit httpd.conf file under [xampp-install-directory]/apache/conf. On Windows, that’s typically C:\xampp.

#LoadModule rewrite_module modules/

So it stays:
LoadModule rewrite_module modules/

Lastly, search for AllowOverride None and replace with AllowOverride All.

In order for the changes to take effect, we need to restart the server.