magyarandras / amp-converter
一个库,可以将HTML文章、博客文章或类似内容转换为AMP(加速移动页面)。
v1.0.8
2023-01-03 23:12 UTC
Requires
- ext-dom: *
- fasterimage/fasterimage: ^1.5
- masterminds/html5: ^2.6
Requires (Dev)
- phpspec/phpspec: ^7.3
README
一个库,可以将HTML文章、博客文章或类似内容转换为 AMP(加速移动页面)。
注意:此库不打算将整个HTML文档转换为AMP,如果您想转换整个页面,应使用更高级的库,例如: Lullabot/amp-library
安装
composer require magyarandras/amp-converter
当前支持的元素
- amp-img
- amp-pan-zoom 中的 amp-img
- 带灯箱的 amp-img
- amp-video
- amp-audio
- amp-iframe(自动添加占位符到iframe中,因此您甚至可以 在上卷中嵌入iframe。)
- amp-youtube
- amp-facebook
- amp-instagram
- amp-twitter
- amp-pinterest
- amp-playbuzz
- amp-gist(Github gist嵌入)
- amp-vimeo
- amp-soundcloud(您可以使用amp-iframe代替)
- amp-vk
- amp-imgur
- amp-dailymotion
- amp-gfycat
用法
简单示例
请确保您的HTML代码不包含HTML5中无效的标签或属性,否则生成的AMP也可能无效。
<?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://#/hX3QmJ707x">https://#/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);
输出
<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>
)
您可以通过手动加载来指定要使用的转换器
<?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);
未知尺寸的图片
如果您的HTML代码中有尺寸未知的图片(您应尽可能避免这种情况),并使用相对URL,您必须将图片的基本URL传递给构造函数。您还可以指定获取单个图片尺寸的时间限制(默认为10秒)。(注意:时间限制适用于每个单独的图片,而不是整个过程)
<?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);
编写自己的转换器
库可能无法直接支持所有功能,但您可以通过自己的转换器(或者如果您需要,可以替换现有的转换器)来扩展它。
例如,考虑以下情况:您在某些文章/博客文章中使用了jQuery倒计时库,并希望将以下代码转换为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>
您可以创建一个自定义转换器类,该类实现了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; } }
使用自定义转换器
<?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);