Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/magyarandras/amp-converter

A PHP library to convert HTML articles, blog posts or similar content to AMP (Accelerated Mobile Pages).
https://github.com/magyarandras/amp-converter

amp amp-html converter-library html php php-library php7 php8

Last synced: 3 days ago
JSON representation

A PHP library to convert HTML articles, blog posts or similar content to AMP (Accelerated Mobile Pages).

Awesome Lists containing this project

README

        

# AMP ⚡ converter library

[![Build Status](https://github.com/magyarandras/amp-converter/workflows/test/badge.svg)](https://github.com/magyarandras/amp-converter/actions)

A library to convert HTML articles, blog posts or similar content to [AMP (Accelerated Mobile Pages)](https://amp.dev).

**Note**: This library is not intended to convert entire HTML documents if you want to convert an entire page you should use a more advanced library, for example: [Lullabot/amp-library](https://github.com/Lullabot/amp-library/)

## Installation:

```
composer require magyarandras/amp-converter
```

## Currently supported elments:
* [x] amp-img
* [x] amp-img in amp-pan-zoom
* [x] amp-img with lightbox
* [x] amp-video
* [x] amp-audio
* [x] amp-iframe(A placeholder is automatically added to the iframes, so you can [embed iframes even above the fold](https://www.youtube.com/watch?v=TqfYmlkHVCs).)
* [x] amp-youtube
* [x] amp-facebook
* [x] amp-instagram
* [x] amp-twitter
* [x] amp-pinterest
* [x] amp-playbuzz
* [x] amp-gist(Github gist embed)
* [x] amp-vimeo
* [ ] amp-soundcloud(You can use amp-iframe instead)
* [x] amp-vk
* [x] amp-imgur
* [x] amp-dailymotion
* [x] amp-gfycat

## Usage:

Simple example:

**Make sure your HTML code doesn't contain tags or attributes invalid in HTML5 otherwise, the generated AMP will be invalid too.**

```php
loadDefaultConverters();

//HTML to convert
$html = '

This is a sample HTML code generated by TinyMCE.



Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.



 



';

//Convert html to amp html
$amphtml = $converter->convert($html);

//Get the necessary amp components
$amp_scripts = $converter->getScripts();

print_r($amphtml);
echo PHP_EOL;
print_r($amp_scripts);

```
The output:
```html

This is a sample HTML code generated by TinyMCE.



Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.



 

```

```
Array
(
[0] =>
[1] =>
)
```

You can specify which converters to use by loading them manually:

```php
addConverter(new AMPImgZoom());
$converter->addConverter(new AMPYoutube());

$amphtml = $converter->convert($html);

$amp_scripts = $converter->getScripts();

print_r($amphtml);
print_r($amp_scripts);

```

## Images with unknown sizes

If you have images with unknown dimensions in your HTML code (you should avoid this situation if possible) and use relative URLs, you must pass the images' base URL to the constructor. You can also specify the time limit for obtaining the size of a single image (the default is 10 seconds). (Note: the time limit applies for every single image, not for the entire process)

```php
'https://example.com', //This base URL will be used if the src of an image is a relative path.
'image_timeout' => 5 //Obtaining the size of a single image (downloading the required data) can't take longer than 5 seconds.
]);

//Load built-in converters
$converter->loadDefaultConverters();

//HTML to convert
$html = '

This is a sample HTML code generated by TinyMCE.


Sample image


';

//Convert html to amp html
$amphtml = $converter->convert($html);

//Get the necessary amp components
$amp_scripts = $converter->getScripts();

print_r($amphtml);
echo PHP_EOL;
print_r($amp_scripts);
```

## Writing your own converters:

The library can't support everything out of the box, but you can extend it with your own converters(or you can replace existing ones if you need).

For example, consider the following: You use a jQuery countdown library in some of your articles/blog posts and you want to convert the following code to AMP.

```html

$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D days %H:%M:%S'));
});
});

```

You can create a custom converter class that implements the TagConverterInterface.

```php
',
''
];

public function convert(\DOMDocument $doc)
{

$query = '//div[@data-countdown]';

$xpath = new \DOMXPath($doc);

$entries = $xpath->query($query);

if ($entries->length > 0) {
$this->necessary_scripts = $this->extension_scripts;
}

foreach ($entries as $tag) {

//Although in this example there isn't any validation, you definitely should check if the date is valid.
$timestamp = strtotime($tag->getAttribute('data-countdown'));

$countdown = $doc->createElement('amp-date-countdown');

$countdown->setAttribute('timestamp-seconds', $timestamp);
$countdown->setAttribute('layout', 'fixed-height');
$countdown->setAttribute('height', '50');

$template = $doc->createElement('template');
$template->setAttribute('type', 'amp-mustache');

$paragraph = $doc->createElement('p');
$paragraph->setAttribute('class', 'p1');

$text = $doc->createTextNode('{{d}} days, {{h}} hours, {{m}} minutes and {{s}} seconds');

$paragraph->appendChild($text);

$template->appendChild($paragraph);
$countdown->appendChild($template);

$tag->parentNode->replaceChild($countdown, $tag);
}

return $doc;
}

public function getNecessaryScripts()
{
return $this->necessary_scripts;
}

}

```

Using the custom converter:

```php
loadDefaultConverters();

$converter->addConverter(new CountdownConverter());

$html = '


Hello!



';

//Convert html to amp html
$amphtml = $converter->convert($html);

//Get the necessary amp components
$amp_scripts = $converter->getScripts();

print_r($amphtml);
print_r($amp_scripts);

```