DEV Community

Cover image for Convert MJML to HTML Using PHP
TechzPad
TechzPad

Posted on

2

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more