wangoviridans / ganon
使用 PHP 编写的快速(HTML DOM)解析器。
dev-master
2014-07-26 04:23 UTC
Requires
- php: >=5.2.0
This package is not auto-updated.
Last update: 2024-09-28 16:09:52 UTC
README
使用 PHP 编写的快速(HTML DOM)解析器。
重要提示
这是一个项目 https://code.google.com/p/ganon/ 的分支。
安装
通过 composer (https://packagist.org.cn/packages/wangoviridans/ganon)
{
"require": {
"wangoviridans/ganon": "dev-master"
}
}
或者直接克隆并将它放置在项目文件夹的任何位置。
$ cd myapp/vendor
$ git clone git://github.com/wangoviridans/ganon.git
使用方法
包含
<?php
require 'vendor/autoload.php';
use Wangoviridans\Ganon;
// Parse the google code website into a DOM
$html = file_get_dom('http://code.google.com/');
在包含 Ganon 并加载 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;
了解更多关于修改元素的信息。
美化
Ganon 还可以帮助您美化代码并正确格式化。
// Beautify the old HTML code and print out the new, formatted code
dom_format($html, array('attributes_case' => CASE_LOWER));
echo $html;