ressio/pharse

最快的PHP HTML解析器

0.2.0 2015-03-24 12:48 UTC

This package is not auto-updated.

Last update: 2024-09-18 07:54:58 UTC


README

最快的PHP HTML解析器

Pharse 是 Ganon 库的分支,并以非常简单的面向对象的方式提供对 HTML/XML 文档的访问。它简化了 DOM 的修改,并使使用类似 CSS3 的查询查找元素变得容易。

Pharse 是

  • 一个通用的分词器
  • 一个 HTML/XML/RSS DOM 解析器
    • 能够操作元素及其属性
    • 支持 HTML5
    • 支持无效的 HTML
    • 支持 UTF8
    • 可以对元素执行高级的类似 CSS3 的查询(如 jQuery -- 支持命名空间)
  • 一个 HTML 美化器(如 HTML Tidy)
    • 压缩 CSS 和 JavaScript
    • 排序属性,更改字符大小写,修正缩进等。
  • 可扩展的
    • 基于当前字符/标记的回调函数解析文档
    • 操作被分离到更小的函数中,以便于覆盖
  • 快速
  • 简单

快速开始

include('path/pharse.php');

// Parse the google code website into a DOM
$html = Pharse::file_get_dom('http://code.google.com/');

在包含 Pharse 并加载 DOM 之后,就可以开始了。

访问

通过类似 CSS3 的选择器和对象模型,访问元素变得简单。

// Find all the paragraph tags with a class attribute and print the
// value of the class attribute
foreach($html('p[class]') as $element) {
  echo $element->class, "<br>\n"; 
}

// Find the first div with ID "gc-header" and print the plain text of
// the parent element (plain text means no HTML tags, just the text)
echo $html('div#gc-header', 0)->parent->getPlainText();

// Find out how many tags there are which are "ns:tag" or "div", but not
// "a" and do not have a class attribute
echo count($html('(ns|tag, div + !a)[!class]');

修改

在找到元素后,可以轻松地修改它们。

// Find all paragraph tags which are nested inside a div tag, change
// their ID attribute and print the new HTML code
foreach($html('div p') as $index => $element) {
  $element->id = "id$index";
}
echo $html;

// Center all the links inside a document which start with "http://"
// and print out the new HTML
foreach($html('a[href ^= "http://"]') as $element) {
  $element->wrap('center');
}
echo $html;

// Find all odd indexed "td" elements and change the HTML to make them links
foreach($html('table td:odd') as $element) {
  $element->setInnerText('<a href="#">'.$element->getPlainText().'</a>');
}
echo $html;

美化

Pharse 还可以帮助您美化代码并正确地格式化它。

// Beautify the old HTML code and print out the new, formatted code
Pharse::dom_format($html, array('attributes_case' => CASE_LOWER));
echo $html;

许可证

Pharse 在 Artistic License/GPL 许可证下发布。