mensbeam / readability
A PHP port of Mozilla's Readability
Requires
- php: >=8.0
- ext-dom: *
- mensbeam/html-parser: ^1.4
- mensbeam/uri: ^1.0
Requires (Dev)
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-09-03 15:51:00 UTC
README
This is a port of Readability to PHP. Much like the other port now maintained by Fivefilters, it is a line-by-line translation, so they do not differ that much. However there are a few differences:
- We support PHP versions as far back as 8.0
- Either
Dom\HTMLDocumentorDOMDocumentinstances are accepted as input - The
mbstringextension is not required (though either it or theintlextension will be used if available) - The API more closely matches the original (though it is not quite the same)
- Unicode characters above U+FFFF are counted twice as in JavaScript
- None of Fivefilters' extra options are supported
- Relative URLs are always resolved
Usage
Distilling a document
As with the JavaScript original, a parsed HTML document is required as input; this document will be modified in-place. Additionally, a document URL is required; the original assumed that document.documentURI is set, but this is usually not true in a PHP context. The same options accepted by Readability are accepted by this port, as an associative array.
use MensBeam\HTML\DOMParser;
use MensBeam\Readability\Readability;
$url = "https://arstechnica.com/";
$html = file_get_contents($url);
// The DOMParser class will accurately parse HTML and return a Dom\HTMLDocument when possible
$document = (new DOMParser)->parseFromString($htnl, "text/html;charset=utf-8");
$options = ['keepClasses' => ["foo", "bar"], 'debug' => true];
$readability = new Readability($document, $url, $options);
$output = $readability->parse();
// The output can be null
if ($output) {
echo $output['content'];
}
Testing a document
Readability includes a much simpler algorithm to determine whether Readability would likely not yield good results, making loading its expensive algorithm not worthwhile. Readability makes this available in a separate file to also save the network transfer of the Readability code, but we include it in the same class as a static method. Our API is otherwise identical.
use MensBeam\HTML\DOMParser;
use MensBeam\Readability\Readability;
$html = file_get_contents($url);
// The DOMParser class will accurately parse HTML and return a Dom\HTMLDocument when possible
$document = (new DOMParser)->parseFromString($htnl, "text/html;charset=utf-8");
$options = ['minScore' => 25];
$output Readability::isProbablyReaderable($document, $options);
var_export($output);