Last active
April 5, 2021 11:33
-
-
Save if0rest/707b4a0c66a164733f0d43e0d9ffdedd to your computer and use it in GitHub Desktop.
Modify buffer content via native DOMDocument or Bitrix API: empty alt tags replacement.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
/** | |
* Работа с DOM-деревом через нативный DOMDocument. | |
*/ | |
AddEventHandler("main", "OnEndBufferContent", "FillEmptyAltTags"); | |
function FillEmptyAltTags(&$content) | |
{ | |
global $APPLICATION; | |
// Возможная конвертация перед импортом HTML | |
// $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'); | |
// $content = html_entity_decode($content, ENT_HTML401); | |
// $content = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $content); | |
$doc = new DOMDocument(); | |
// $doc->preserveWhiteSpace = false; // Указание не убирать лишние пробелы и отступы. По умолчанию true. | |
// Тег <meta http-equiv="Content-Type"... /> важно передавать явно, даже если он дублируется. | |
// Иначе эрмитаж кракозябрит. | |
if (@$doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'.$content)) | |
{ | |
$images = $doc->getElementsByTagName('img'); | |
$i = 1; | |
foreach ($images as $img) | |
{ | |
if (!$img->hasAttribute('alt') || strlen(trim($img->getAttribute('alt'))) === 0) | |
{ | |
$keywords = $APPLICATION->GetProperty('keywords'); | |
if (strlen($keywords)) | |
$img->setAttribute('alt', $keywords.' '.$i++); | |
} | |
} | |
$content = $doc->saveHTML(); | |
} | |
} | |
/** | |
* Работа с DOM-деревом через Bitrix API. | |
*/ | |
AddEventHandler("main", "OnEndBufferContent", "FillEmptyAltTags"); | |
function FillEmptyAltTags(&$content) | |
{ | |
global $APPLICATION; | |
$doс = new \Bitrix\Main\Web\DOM\Document; | |
$doс->loadHTML($content); | |
$i = 1; | |
$images = $doс->getElementsByTagName('img'); | |
foreach ($images as $img) | |
{ | |
if (!$img->hasAttribute('alt') || strlen(trim($img->getAttribute('alt'))) === 0) | |
{ | |
$keywords = $APPLICATION->GetProperty('keywords'); | |
$img->setAttribute('alt', $keywords.' '.$i++); | |
} | |
} | |
$content = $doс->saveHTML(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment