DEV Community

Cover image for Convert MJML to HTML Using PHP
TechzPad
TechzPad

Posted on

Convert MJML to HTML Using PHP

The MJML offers a variety of methods for converting MJML to HTML, including a Node tool, a CLI tool, and a website where you may manually convert MJML. You can also get auto-completion for MJML in your preferred editor by using one of the many plugins.

Our most recent package, spatie/mjml-php, uses PHP to convert MJML to HTML. It’s a skillfully made, user-friendly wrapper for the Node tool. Instead of needing to develop every feature in PHP, we can just use it all by using the Node tool below. But you don’t need to worry about any of this as you’re using the PHP package.

The package can be installed using composer:

composer require spatie/mjml-php
Additionally, check that your project has access to the Node MJML package.

npm install mjml
With this out of the way, you can start converting MJML.

use Spatie\Mjml\Mjml;
// let's assume $mjml contains the MJML you want to convert
$html = Mjml::new()->toHtml($mjml);

There are a couple of methods, such as beautify, hideComments(), minify() to customize the conversion process.

use Spatie\Mjml\Mjml;
// let's assume $mjml contains the MJML you want to convert
$minifiedHtml = Mjml::new()->minify()->toHtml($mjml);

We also added a method that you can use to ensure the given MJML is valid.

use Spatie\Mjml\Mjml;
Mjml::new()->canConvert($mjml); // returns a boolean

From the package’s README file, here is the simplest usage:

use Spatie\Mjml\Mjml;
$mjml = <<<'MJML'
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text invalid-attribute>Hello World</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
MJML;
$html = Mjml::new()->toHtml($mjml);

If you try step by step process here is the guide on How to Convert MJML to HTML Using PHP.

Top comments (0)