Skip to content

Instantly share code, notes, and snippets.

@callaginn
Last active July 7, 2020 18:06
Show Gist options
  • Save callaginn/54f49adcddc640e8080fc4733ca97e89 to your computer and use it in GitHub Desktop.
Save callaginn/54f49adcddc640e8080fc4733ca97e89 to your computer and use it in GitHub Desktop.
Convert MJML to HTML With PHP (Zero Fuss Method)
<?php
$home = `printf ~`;
putenv("HOME=$home");
putenv('PATH=$PATH:/bin:/usr/bin:/usr/local/bin:$HOME/bin');
function mjml2html($mjml) {
$temp = tempnam('', '');
file_put_contents($temp, $mjml);
$html = shell_exec('. ~/.bashrc; mjml ' . $temp . ' --config.minify true');
unlink($temp);
return $html;
}
?>
@callaginn
Copy link
Author

callaginn commented Jul 7, 2020

I recently developed a pretty simple method for converting MJML syntax to HTML on an email system we built on the Twig templating engine. I'm posting it here, since there don't seem to be a lot of dead easy methods / instructions for doing this.

This method requires the mjml binary to be installed on your server. MJML can be installed via npm install -g mjml.

Every time this function is run, it saves your mjml code as a temporary file on your server and passes the pathname to the mjml binary. After the html is rendered, that file is deleted.

Confirmed to work on Dreamhost servers using PHP 7.4. There's a chance other servers "might" need adjustments to the $HOME and $PATH variables. Or they might not need those lines at all...

To use it, simply do this:
$html = mjml2html($mjml);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment