Convert HTML to Array or JSON
$ composer require shtrihstr/html-serializer
$html = new HtmlSerializer\Html('<div class="content"><p>Hello World</p><img src="img.png" alt="" class="image" /></div>');
$json = $html->toJson();
[
{
"node": "div",
"attributes": {
"class": "content"
},
"children": [
{
"node": "p",
"children": [
{
"node": "text",
"text": "Hello World"
}
]
},
{
"node": "img",
"attributes": {
"src": "img.png",
"alt": "",
"class": "image"
}
}
]
}
]
$array = $html->toArray();
[
[
'node' => 'div',
'attributes' => [
'class' => 'content',
],
'children' => [
[
'node' => 'p',
'children' => [
[
'node' => 'text',
'text' => 'Hello World',
],
]
],
[
'node' => 'img',
'attributes' => [
'src' => 'img.png',
'alt' => '',
'class' => 'image',
]
],
],
],
]
$html = new HtmlSerializer\Html('<div style="color: red; background: url(img.png?foo;bar)">Hello World</div>');
$html->parseCss(); // enabled by default
$json = $html->toJson();
[
{
"node": "div",
"attributes": {
"style": {
"color": "red",
"background": "url(img.png?foo;bar)"
}
},
"children": [
{
"node": "text",
"text": "Hello World"
}
]
}
]
$html->parseCss(false);
[
{
"node": "div",
"attributes": {
"style": "color: red; background: url(img.png?foo;bar)"
},
"children": [
{
"node": "text",
"text": "Hello World"
}
]
}
]
$html = new HtmlSerializer\Html('<div> <p> foo</p> <span> bar </span> </div>');
$html->removeEmptyStrings(); // enabled by default
$json = $html->toJson();
[
{
"node": "div",
"children": [
{
"node": "p",
"children": [
{
"node": "text",
"text": " foo"
}
]
},
{
"node": "span",
"children": [
{
"node": "text",
"text": " bar "
}
]
}
]
}
]
$html->removeEmptyStrings(false)
[
{
"node": "div",
"children": [
{
"node": "text",
"text": " "
},
{
"node": "p",
"children": [
{
"node": "text",
"text": " foo"
}
]
},
{
"node": "text",
"text": " "
},
{
"node":"span",
"children": [
{
"node": "text",
"text": " bar "
}
]
},
{
"node": "text",
"text": " "
}
]
}
]