У меня есть этот крошечный класс, который поможет мне заменить пользовательские теги действительными тегами HTML.Моя проблема в том, что он заменяет только первый пользовательский тег по любой причине.Моя догадка заключается в том, что я где-то нарушаю ссылку, но не могу понять, где ... Прокрутите вниз до нижней части этого поста, чтобы увидеть фактический результат и ожидаемый результат.
<?php
class DomParser {
protected $tags = [];
protected $document;
public function __construct($html) {
$this->document = new DOMDocument();
$this->document->loadXML($html);
}
public function addTag(string $name, callable $callable) {
$this->tags[$name] = $callable;
}
public function replace() {
foreach ($this->tags as $name => $callable) {
$elements = $this->document->getElementsByTagName($name);
foreach ($elements as $element) {
$callable($element, $this->document);
}
}
return $this->document->saveHTML();
}
}
Пример кода для запуска класса:
<?php
require_once 'DomParser.php';
//require_once 'RenameTag.php';
//require_once 'Container.php';
$html = '<html>
<container>
<col>
<p>
<test attribute="test" attribute2="this">test<br />test2</test>
</p>
</col>
<col>
test col
</col>
</container>
<container fluid="test"><test>dsdshsh</test></container>
</html>';
$parser = new DomParser($html);
//$parser->addTag('test', RenameTag::create('othertag'));
//$parser->addTag('container', Container::create());
$parser->addTag('col', function($oldTag) {
$document = $oldTag->ownerDocument;
$newTag = $document->createElement('div');
$oldTag->parentNode->replaceChild($newTag, $oldTag);
foreach (iterator_to_array($oldTag->childNodes) as $child) {
$newTag->appendChild($oldTag->removeChild($child));
}
$newTag->setAttribute('class', 'col');
});
echo $parser->replace();
Я получаю такой результат:
<html>
<container>
<div class="col">
<p>
<test attribute="test" attribute2="this">test<br>test2</test>
</p>
</div>
<col>
</container>
<container fluid="true"><test>dsdshsh</test></container>
</html>
Ожидаемый результат должен быть:
<html>
<container>
<div class="col">
<p>
<test attribute="test" attribute2="this">test<br>test2</test>
</p>
</div>
<div class="col">
test col
</div>
</container>
<container fluid="test"><test>dsdshsh</test></container>
</html>