commnetivity / purehtml
利用PHP的DOM功能进行HTML处理
v1.0.6
2018-11-27 18:02 UTC
README
(实际上,这个类是有效的,但是构建失败,因为还没有为Travis-CI设置PHP Unit测试和说明)
PureHTML DOM处理器
这个库利用PHP原生DOM处理器的速度和灵活性,让您解析、剥离、拼接甚至美化您的HTML页面。
<?php $buffer = new PureHTML(); $template = file_get_contents("template.html"); $html->scan($template); // Every call to scan() will build up $buffer with seen JS and CSS assets. $html = $buffer->scrub($template); // Scrub the template of JS and CSS assets /* Load up your dynamic content via DOM (optional, you can also use use a string of HTML) */ ob_start(); echo "Hello, world. I am to be spliced into the html div container with the id of \"content\"."; echo '<link href="helloworld.css" />'; $content = ob_get_contents(); $domOfDynamic = new DOMDocument(); // Create DOM object $domOfDynamic->loadHTML($content); // Load DOM object with content $frag = $domOfDynamic->saveHTML(); // Save the DOM into a string. /* Scan fragment for JS and CSS */ $buffer->scan($frag); // If you want the buffer to contain JS and CSS resources in the order they are collected, then you must call this on each new HTML fragment or template you want to include. $scrubbed_dynamic = $buffer->scrub($frag); // Now we scrub the fragment of JS and CSS $template = $buffer->splice($template, $scrubbed_dynamic, "content"); // Now we splice the new fragment into templates. The "content" is the id of an html tag found in the template. In this case, it's <div id="content"></div> $html = $buffer->rebuild($template); // When ready may now reassemble the compiled template. echo $buffer->beautifyDOM($html); // Optionally use this to format the output to be a lot more human readable.
安装
开始使用最简单的方法是使用 Composer 安装 commnetivity/purehtml
{ "require": { "commnetivity/purehtml": "dev-master*" } }
<?php require("vendor/autoload.php"); ... your script ...
美化DOM函数说明
这是一个PHP函数,通过添加缩进和换行使HTML文档的输出更易于阅读。以下是它的工作原理分析
- 该函数接受两个参数:
$doc
,它是一个DOMDocument
对象,表示HTML文档,以及$depth
,它是当前递归的深度(默认值为1)。 - 它创建一个新的
DOMXPath
对象以查询HTML文档。 - 它使用XPath遍历HTML文档中的所有文本节点,并从它们的值中删除任何前导或尾随空白(包括换行符、回车符和空格)。如果结果值是一个空字符串,则删除该节点。
- 它定义了一个名为
$format
的递归函数,该函数接受三个参数:$dom
,它是一个表示HTML文档的DOMDocument
对象,$currentNode
,它是当前要格式化的节点,以及$depth
,它是当前递归的深度。 - 如果
$currentNode
为假,则删除$dom
的第一个子节点(通常是<!DOCTYPE>
声明)并将$currentNode
设置为$dom
本身。 - 它通过检查当前节点是否为文本节点并且其父节点只有一个子节点来确定当前节点是否应该缩进。如果是,则将
$indentCurrent
设置为false;否则,设置为true。 - 如果
$indentCurrent
为true并且$depth
大于1,则创建一个新的文本节点,包含一个换行符和$depth
个空格,并将其插入到$currentNode
之前。 - 它遍历
$currentNode
的所有子节点,并对每个子节点递归调用$format
,传递$dom
、子节点和$depth+1
。 - 如果任何子节点进行了缩进,则将
$indentClosingTag
设置为true。 - 如果
$indentClosingTag
为true,则创建一个新的文本节点,包含一个换行符和$depth
个空格(除非当前节点是<html>
标签),并将其追加到$currentNode
。 - 该函数使用
$doc
作为第一个参数调用$format
,不传递第二个参数(将$currentNode
设置为false),从而格式化整个HTML文档。 - 该函数返回带
<!DOCTYPE>
声明的格式化HTML文档。