All formats

PHP eBook

LanguagePHP 8.1+
LicenseMIT
Repositorygithub.com/kiwilan/php-ebook
DocumentationREADME
Depends onkiwilan/php-archive, kiwilan/php-xml-reader
Read / writeyes / no (.fb2)

PHP eBook reads e-book metadata with one API for EPUB, MOBI, FB2, PDF and comics. For FictionBook files it parses the XML and fills the Ebook model from title-info and publish-info: title, authors, language, genre and keywords (as tags), annotation (as description), series and number from sequence, publisher, publication year and ISBN. It decodes the cover from the binary element that coverpage points to.

It also exposes a parsed view of the description, body and binaries for custom processing. It doesn’t render text or write FB2. The same API reads EPUB and MOBI files.

Installation#

Shell
composer require kiwilan/php-ebook

Basic usage: read FB2 metadata#

PHP
<?php
require 'vendor/autoload.php';

use Kiwilan\Ebook\Ebook;

$ebook = Ebook::read('book.fb2');
if ($ebook === null) {
    exit("cannot read file\n");
}

echo 'Title:    ', $ebook->getTitle(), "\n";
foreach ($ebook->getAuthors() as $author) {
    echo 'Author:   ', $author->getName(), "\n";
}
echo 'Language: ', $ebook->getLanguage(), "\n";
echo 'Tags:     ', implode(', ', $ebook->getTags()), "\n";
if ($ebook->hasSeries()) {
    echo 'Series:   ', $ebook->getSeries(), ' #', $ebook->getVolume(), "\n";
}
echo 'Annotation: ', $ebook->getDescriptionAdvanced()?->toString(300), "\n";

getDescriptionAdvanced()->toString($limit) turns the annotation markup into plain text.

How to extract the cover from an FB2 file#

PHP
$ebook = Ebook::read('book.fb2');
if ($ebook?->hasCover()) {
    $ebook->getCover()->saveTo('cover.jpg');
}

How to access the parsed FB2 description#

PHP
$parser = Ebook::read('book.fb2')?->getParser()?->getFb2()?->getParser();
$desc = $parser?->getDescription();

echo $desc?->title?->bookTitle, "\n";
foreach ($desc?->title?->author ?? [] as $a) {
    echo $a->firstName, ' ', $a->lastName, "\n";
}
echo 'Sequence: ', $desc?->title?->sequence?->name, ' ', $desc?->title?->sequence?->number, "\n";
echo 'ISBN: ', $desc?->publish?->isbn, "\n";
echo 'Program: ', $desc?->document?->programUsed, "\n";

$parser->getBody() returns the body as nested arrays and $parser->getBinary() the binary elements.

How to build a catalog of an FB2 collection#

PHP
foreach (glob('library/*.fb2') as $path) {
    $ebook = Ebook::read($path);
    if ($ebook === null) {
        continue;
    }
    printf("%s | %s | %s\n",
        $ebook->getAuthorMain()?->getName(),
        $ebook->getTitle(),
        $ebook->getMetaTitle()?->getSlug());
}

Tips#