| 1 |
HtmlFormatter is a library spun off MediaWiki that allows you to load HTML into DomDocument, perform manipulations on it, and then return a HTML string. |
| 2 |
|
| 3 |
Usage |
| 4 |
----- |
| 5 |
|
| 6 |
```php |
| 7 |
use HtmlFormatter\HtmlFormatter; |
| 8 |
// Load HTML that already has doctype and stuff |
| 9 |
$formatter = new HtmlFormatter( $html ); |
| 10 |
|
| 11 |
// ...or one that doesn't have it |
| 12 |
$formatter = new HtmlFormatter( HtmlFormatter::wrapHTML( $html ) ); |
| 13 |
|
| 14 |
// Add rules to remove some stuff |
| 15 |
$formatter->remove( 'img' ); |
| 16 |
$formatter->remove( [ '.some_css_class', '#some_id', 'div.some_other_class' ] ); |
| 17 |
// Only the above syntax is supported, not full CSS/jQuery selectors |
| 18 |
|
| 19 |
// These tags get replaced with their inner HTML, |
| 20 |
// e.g. <tag>foo</tag> --> foo |
| 21 |
// Only tag names are supported here |
| 22 |
$formatter->flatten( 'span' ); |
| 23 |
$formatter->flatten( [ 'code', 'pre' ] ); |
| 24 |
|
| 25 |
// Actually perform the removals |
| 26 |
$formatter->filterContent(); |
| 27 |
|
| 28 |
// Direct DomDocument manipulations are possible |
| 29 |
$formatter->getDoc()->createElement( 'p', 'Appended paragraph' ); |
| 30 |
|
| 31 |
// Get resulting HTML |
| 32 |
$processedHtml = $formatter->getText(); |
| 33 |
``` |
| 34 |
|
| 35 |
License |
| 36 |
------- |
| 37 |
Copyright 2011-2024 MediaWiki contributors |
| 38 |
|
| 39 |
This program is free software; you can redistribute it and/or modify |
| 40 |
it under the terms of the GNU General Public License as published by |
| 41 |
the Free Software Foundation; either version 2 of the License, or |
| 42 |
(at your option) any later version. |
| 43 |
|
| 44 |
This program is distributed in the hope that it will be useful, |
| 45 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 46 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 47 |
GNU General Public License for more details. |
| 48 |
|
| 49 |
You should have received a copy of the GNU General Public License along |
| 50 |
with this program; if not, write to the Free Software Foundation, Inc., |
| 51 |
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 52 |
<http://www.gnu.org/copyleft/gpl.html> |