- var_export: documentation ( source)
- str_replace: documentation ( source)
- trim: documentation ( source)
- libxml_use_internal_errors: documentation ( source)
<?php
$codes = <<<'CODES'
[column]
[row]
[column][/column]
[column][/column]
[/row]
[/column]
CODES;
$html = str_replace(['[', ']'], ['<', '>'], $codes);
libxml_use_internal_errors(true);
$dom = new \DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach($dom->getElementsByTagName('row') as $row) {
foreach($row->getElementsByTagName('column') as $column) {
$column->appendChild($dom->createTextNode('test'));
$column->setAttribute('class', 'test');
}
}
$tags = getTags($dom->documentElement);
echo var_export($tags, true);
function getTags($element, $tags = [])
{
$tag = ['tagName' => $element->tagName];
if ($element->hasAttributes()) {
foreach ($element->attributes as $attribute) {
$tag['attributes'][$attribute->name] = $attribute->value;
}
}
if ('' !== ($nodeValue = trim($element->textContent)) && false === $element->hasChildNodes()) {
$tag['nodeValue'] = $nodeValue;
}
if ($element->hasChildNodes()) {
foreach ($element->childNodes as $childElement) {
if ($childElement->nodeType !== XML_ELEMENT_NODE) {
continue;
}
$tag[] = getTags($childElement, $tags);
}
}
$tags[] = $tag;
return $tags;
}