PHP eBook
| Language | PHP 8.1+ |
|---|---|
| License | MIT |
| Repository | github.com/kiwilan/php-ebook |
| Documentation | README |
| Depends on | kiwilan/php-archive, kiwilan/php-xml-reader (no extension needed for MOBI) |
| Read / write | yes / no (.mobi, .azw, .azw3, .kf8, .prc; metadata and cover only) |
PHP eBook reads e-book metadata with one API for all formats. For Mobipocket and Kindle files it parses the Palm database, the PalmDOC and MOBI headers and the EXTH records in pure PHP, and maps them to the Ebook model: title (EXTH 503), authors (100), publisher (101), description (103), ISBN (104), subjects (105), publishing date (106), ASIN (113) and language (524). It also extracts the embedded cover image.
It doesn’t decompress or return the book’s text, and it can’t read KFX files despite accepting the extension. The cover it extracts is the embedded image, which can be small; the README suggests converting to EPUB with Calibre for better covers. The same API reads EPUB and FB2.
Installation#
Shell
composer require kiwilan/php-ebook
Basic usage: read MOBI metadata#
PHP
<?php
require 'vendor/autoload.php';
use Kiwilan\Ebook\Ebook;
$ebook = Ebook::read('book.azw3');
if ($ebook === null || !$ebook->isMobi()) {
exit("not a MOBI file\n");
}
echo 'Title: ', $ebook->getTitle(), "\n";
foreach ($ebook->getAuthors() as $author) {
echo 'Author: ', $author->getName(), "\n";
}
echo 'Publisher: ', $ebook->getPublisher(), "\n";
echo 'Language: ', $ebook->getLanguage(), "\n";
echo 'Published: ', $ebook->getPublishDate()?->format('Y-m-d'), "\n";
echo 'Description: ', $ebook->getDescription(), "\n";
foreach ($ebook->getIdentifiers() as $id) {
echo 'Identifier: ', $id->getValue(), ' (', $id->getScheme(), ")\n"; // isbn, asin, source
}
How to extract the cover from a MOBI or AZW3 file#
PHP
$ebook = Ebook::read('book.mobi');
if ($ebook?->hasCover()) {
$ebook->getCover()->saveTo('cover.jpg');
}
How to read raw EXTH records#
The MOBI module exposes the parsed headers:
PHP
use Kiwilan\Ebook\Formats\Mobi\Parser\MobiReader;
$parser = Ebook::read('book.mobi')?->getParser()?->getMobi()?->getParser();
if ($parser !== null && $parser->isValid()) {
echo 'ASIN: ', $parser->get(MobiReader::ASIN_113), "\n";
print_r($parser->get(MobiReader::AUTHOR_100, true)); // all author records as an array
print_r($parser->getExthRecords());
}
How to scan a folder of Kindle books#
PHP
foreach (glob('books/*.{mobi,azw,azw3}', GLOB_BRACE) as $path) {
$ebook = Ebook::read($path);
if ($ebook === null) {
continue;
}
printf("%-40s %s\n", $ebook->getTitle(), $ebook->getAuthorMain()?->getName());
}
Tips#
Ebook::isValid($path)checks a file before reading it.- Encrypted Amazon books usually still have readable EXTH metadata, because DRM encrypts only the text records.