magyarandras/amp-converter
Composer 安装命令:
composer require magyarandras/amp-converter
包简介
A library to convert HTML articles, blog posts or similar content to AMP (Accelerated Mobile Pages).
关键字:
README 文档
README
A library to convert HTML articles, blog posts or similar content to AMP (Accelerated Mobile Pages).
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
Installation:
composer require magyarandras/amp-converter
Currently supported elments:
- amp-img
- amp-img in amp-pan-zoom
- amp-img with lightbox
- amp-video
- amp-audio
- amp-iframe(A placeholder is automatically added to the iframes, so you can embed iframes even above the fold.)
- amp-youtube
- amp-facebook
- amp-instagram
- amp-twitter
- amp-pinterest
- amp-playbuzz
- amp-gist(Github gist embed)
- amp-vimeo
- amp-soundcloud(You can use amp-iframe instead)
- amp-vk
- amp-imgur
- amp-dailymotion
- 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 use magyarandras\AMPConverter\Converter; /* If you have images with unknown dimensions in your HTML code and use relative URLs, you must pass the images' base URL to the constructor. Examples: $converter = new Converter('https://example.com'); $converter = new Converter('https://cdn.example.com'); */ $converter = new Converter(); //Load built-in converters $converter->loadDefaultConverters(); //HTML to convert $html = ' <p><strong>This is a sample HTML code generated by TinyMCE.</strong></p> <p><strong><img src="https://cdn.example.com/photo/example_960_720.jpg" alt="" width="960" height="640" /></strong></p> <p><span style="font-family: \'times new roman\', times;">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.</span></p> <p style="text-align: center;"><iframe src="https://www.youtube.com/embed/gYJ03GyrSrM" width="560" height="314" allowfullscreen="allowfullscreen"></iframe></p> <p style="text-align: center;"> </p> <blockquote class="twitter-tweet"> <p dir="ltr" lang="en">Check out the latest post on the AMP Blog to learn how <a href="https://twitter.com/AdobeExpCloud?ref_src=twsrc%5Etfw">@AdobeExpCloud</a> has been working to seamless integrate AMP support into its applications ⚡<br /><br />Learn more here 👉 <a href="https://t.co/hX3QmJ707x">https://t.co/hX3QmJ707x</a></p> — AMP Project (@AMPhtml) <a href="https://twitter.com/AMPhtml/status/1248666798901194753?ref_src=twsrc%5Etfw">April 10, 2020</a></blockquote> '; //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:
<p><strong>This is a sample HTML code generated by TinyMCE.</strong></p> <p><strong><amp-img src="https://cdn.example.com/photo/example_960_720.jpg" width="960" height="640" alt layout="responsive"></amp-img></strong></p> <p><span>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.</span></p> <p><amp-youtube data-videoid="gYJ03GyrSrM" width="480" height="270" layout="responsive"></amp-youtube></p> <p> </p> <amp-twitter width="375" height="472" layout="responsive" data-tweetid="1248666798901194753"></amp-twitter>
Array
(
[0] => <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
[1] => <script async custom-element="amp-twitter" src="https://cdn.ampproject.org/v0/amp-twitter-0.1.js"></script>
)
You can specify which converters to use by loading them manually:
<?php use magyarandras\AMPConverter\Converter; use magyarandras\AMPConverter\TagConverter\AMPImgZoom; use magyarandras\AMPConverter\TagConverter\AMPYoutube; //PHP 7+ syntax: //use magyarandras\AMPConverter\TagConverter\{AMPImgZoom,AMPYoutube} $converter = new Converter(); $converter->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 use magyarandras\AMPConverter\Converter; $converter = new Converter([ 'image_base_url' => '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 = ' <p><strong>This is a sample HTML code generated by TinyMCE.</strong></p> <p><strong><img src="images/picture.jpg" alt="Sample image" /></strong></p> '; //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.
<!-- The following line should be replaced with amp-date-countdown component --> <div data-countdown="2038/01/19"></div> <!-- Countdown library: http://hilios.github.io/jQuery.countdown/examples/multiple-instances.html --> <script> $('[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')); }); }); </script>
You can create a custom converter class that implements the TagConverterInterface.
<?php class CountdownConverter implements \magyarandras\AMPConverter\TagConverterInterface { private $necessary_scripts = []; private $extension_scripts = [ '<script async custom-element="amp-date-countdown" src="https://cdn.ampproject.org/v0/amp-date-countdown-0.1.js"></script>', '<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>' ]; 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 require_once 'vendor/autoload.php'; require_once 'CountdownConverter.php'; use magyarandras\AMPConverter\Converter; $converter = new Converter(); //Load built-in converters $converter->loadDefaultConverters(); $converter->addConverter(new CountdownConverter()); $html = '<div><h1>Hello!</h1><div data-countdown="2038/01/19"></div></div>'; //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);
magyarandras/amp-converter 适用场景与选型建议
magyarandras/amp-converter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 155.47k 次下载、GitHub Stars 达 65, 最近一次更新时间为 2019 年 05 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「html」 「converter」 「amp」 「AMPHTML」 「amp-html」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 magyarandras/amp-converter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 magyarandras/amp-converter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 magyarandras/amp-converter 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Texy converts plain text in easy to read Texy syntax into structurally valid (X)HTML. It supports adding of images, links, nested lists, tables and has full support for CSS. Texy supports hyphenation of long words (which reflects language rules), clickable emails and URL (emails are obfuscated again
Tools to convert between .NET and PHP date formats
Encode integer IDs using a preset or customized symbol set
HTML and form generation
TCMB Currenct Converter
A modern HTML DOM parser for PHP using DOMDocument and Symfony CssSelector.
统计信息
- 总下载量: 155.47k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 65
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2019-05-25