shtrihstr / html-serializer
将HTML转换为JSON
dev-master
2016-08-18 12:44 UTC
Requires (Dev)
- phpunit/phpunit: ^5.5
This package is not auto-updated.
Last update: 2024-09-20 22:48:22 UTC
README
将HTML转换为数组或JSON
安装
$ composer require shtrihstr/html-serializer
使用
HTML到JSON
$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"
}
}
]
}
]
HTML到数组
$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',
]
],
],
],
]
内联CSS
$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": " "
}
]
}
]