PHPackages                             controlaltjeff/p7m-fattura-decoder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. controlaltjeff/p7m-fattura-decoder

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

controlaltjeff/p7m-fattura-decoder
==================================

PHP library per decodificare file PKCS#7 (.p7m) ed estrarre il contenuto XML.

v1.0.3(1mo ago)05MITPHPPHP &gt;=5.3CI passing

Since Jun 13Pushed 1mo agoCompare

[ Source](https://github.com/controlaltjeff/p7m-fattura-decoder)[ Packagist](https://packagist.org/packages/controlaltjeff/p7m-fattura-decoder)[ RSS](/packages/controlaltjeff-p7m-fattura-decoder/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (5)Versions (5)Used By (0)

P7M Decoder — PHP Fattura Elettronica PKCS#7
============================================

[](#p7m-decoder--php-fattura-elettronica-pkcs7)

[![CI](https://github.com/controlaltjeff/p7m-fattura-decoder/actions/workflows/ci.yml/badge.svg)](https://github.com/controlaltjeff/p7m-fattura-decoder/actions/workflows/ci.yml)[![Packagist Version](https://camo.githubusercontent.com/10789100388890ce4a244e7bdb26de45a309bf32b584b984f29b76589f7ae57b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f6e74726f6c616c746a6566662f70376d2d666174747572612d6465636f646572)](https://packagist.org/packages/controlaltjeff/p7m-fattura-decoder)[![Packagist Downloads](https://camo.githubusercontent.com/0fce886fb16297a6dcbb17348f3e15b0c136b3a347cad7c28d4c6b7b1c328a45/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f6e74726f6c616c746a6566662f70376d2d666174747572612d6465636f646572)](https://packagist.org/packages/controlaltjeff/p7m-fattura-decoder)[![PHP Version Require](https://camo.githubusercontent.com/f2d9c6c920c5c5175c700b2687cb5b568b03a2817b83c2d3349acb29d477c057/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f636f6e74726f6c616c746a6566662f70376d2d666174747572612d6465636f646572)](https://packagist.org/packages/controlaltjeff/p7m-fattura-decoder)[![License](https://camo.githubusercontent.com/dd055082c5a202a925165ebe68302bc64cafb627e9c02f54a5e79e628e75deb6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636f6e74726f6c616c746a6566662f70376d2d666174747572612d6465636f646572)](LICENSE)[![PHPStan Level](https://camo.githubusercontent.com/ff3c7f8c8667ce643f47e74532748f673482a5f95d7d4269f925f2eebbe5117e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230382d627269676874677265656e)](https://phpstan.org/)

PHP library per decodificare file `.p7m` (PKCS#7 signed) ed estrarre il contenuto XML. Progettata per la [Fattura Elettronica italiana](https://www.agenziaentrate.gov.it/portale/web/guest/schede/fatturapa) ma funziona con qualsiasi file P7M.

Indice
------

[](#indice)

- [Installazione](#installazione)
- [Requisiti](#requisiti)
- [Utilizzo rapido](#utilizzo-rapido)
- [API](#api)
- [Come funziona](#come-funziona)
- [Casi d'uso](#casi-duso)
- [Sviluppo](#sviluppo)
- [Contribuire](#contribuire)
- [Licenza](#licenza)

Installazione
-------------

[](#installazione)

```
composer require controlaltjeff/p7m-fattura-decoder
```

Requisiti
---------

[](#requisiti)

- **PHP 5.3+** (runtime) / PHP 8.1+ (strumenti di sviluppo)
- `ext-dom`, `ext-libxml` (sempre richieste)
- `ext-openssl` (consigliata — usata come strategia di decodifica primaria)
- `openssl` CLI (opzionale — usato per la verifica DER/PEM)

> **Nota per ambienti PHP 5.3/7.x**: gli strumenti di sviluppo (PHPUnit, PHPStan) richiedono PHP 8.1+. Installa con `--no-dev` per evitare conflitti:
>
> ```
> composer require controlaltjeff/p7m-fattura-decoder --no-dev
> ```

Utilizzo rapido
---------------

[](#utilizzo-rapido)

```
use Controlaltjeff\P7MDecoder\P7MDecoder;

// Decodifica da file
$xml = P7MDecoder::decodeFile('fattura.xml.p7m');

// Decodifica da stringa
$xml = P7MDecoder::decodeString($p7mContent);

if ($xml === null) {
    throw new \RuntimeException('Impossibile decodificare il file P7M');
}

// Correzioni automatiche applicate durante la decodifica
$corrections = P7MDecoder::getLastCorrections();
foreach ($corrections as $fix) {
    echo "Tag corretto: {$fix['from']} → {$fix['to']}\n";
}
```

API
---

[](#api)

### `P7MDecoder::decodeFile(string $path): ?string`

[](#p7mdecoderdecodefilestring-path-string)

Decodifica un file `.p7m` e restituisce il suo contenuto XML, oppure `null` in caso di errore.

```
$xml = P7MDecoder::decodeFile('/percorso/della/fattura.p7m');
```

### `P7MDecoder::decodeString(string $content): ?string`

[](#p7mdecoderdecodestringstring-content-string)

Decodifica contenuto P7M da una stringa (DER, PEM, Base64, o XML valido).

```
$content = file_get_contents('fattura.p7m');
$xml = P7MDecoder::decodeString($content);
```

### `P7MDecoder::getLastCorrections(): array`

[](#p7mdecodergetlastcorrections-array)

Restituisce la lista delle correzioni ai tag applicate durante l'ultimo'operazione di decodifica.

```
// Dopo una chiamata a decodeFile/decodeString
$corrections = P7MDecoder::getLastCorrections();
// Restituisce: [['from' => 'DettHaglioLinee', 'to' => 'DettaglioLinee', 'distance' => 1], ...]
```

Come funziona
-------------

[](#come-funziona)

La libreria tenta la decodifica usando **8 strategie** in ordine, fermandosi al primo successo:

\#StrategiaDescrizione1Plain XMLSe il contenuto e' gia' XML valido, lo restituisce direttamente2OpenSSL DER`openssl smime -verify -inform DER`3Base64 → DERDecodifica Base64 + verifica DER4OpenSSL PEM`openssl smime -verify -inform PEM` (include conversione Base64 → PEM)5PHP openssl\_pkcs7\_verify()Fallback via estensione PHP6Estrazione manualeRicerca fragment XML nel binario7Correzione tagRicerca fuzzy (Levenshtein) su tag XML danneggiati8Base64 + estrazione manualeDecodifica Base64 + fragment XML### Correzioni automatiche

[](#correzioni-automatiche)

Oltre alla decodifica, la libreria applica correzioni automatiche su:

- **Tag XML** — Correzione fuzzy con distance ≤ 1 rispetto alla lista tag FatturaPA validi
- **Errori OCR/encoding** — 30+ pattern di correzione per errori tipici di OCR e trasmissione:
    - `UnitaMisurah` → `UnitaMisura`
    - `DettHaglioLinee` → `DettaglioLinee`
    - `Quant2ita` → `Quantita`
    - e molti altri...

Le correzioni applicate sono accessibili via `P7MDecoder::getLastCorrections()`.

Casi d'uso
----------

[](#casi-duso)

### Elaborare file FatturaPA ricevuti dal SDI

[](#elaborare-file-fatturapa-ricevuti-dal-sdi)

```
use Controlaltjeff\P7MDecoder\P7MDecoder;

// Decodifica un file FatturaPA .p7m ricevuto dal SDI
$xml = P7MDecoder::decodeFile('IT01234567890_FPR12_001.xml.p7m');

if ($xml === null) {
    die('Decodifica fallita');
}

// Analizza l'XML
$dom = new DOMDocument();
$dom->loadXML($xml);

// Accedi ai dati della fattura
$xpath = new DOMXPath($dom);
$numeroFattura = $xpath->query('//Numero')->item(0)->nodeValue;
$importoTotale = $xpath->query('//ImportoTotaleDocumento')->item(0)->nodeValue;
```

### Elaborare piu' file

[](#elaborare-piu-file)

```
use Controlaltjeff\P7MDecoder\P7MDecoder;

$files = glob('/percorso/delle/fatture/*.p7m');
foreach ($files as $file) {
    $xml = P7MDecoder::decodeFile($file);
    if ($xml !== null) {
        file_put_contents(str_replace('.p7m', '.xml', $file), $xml);
        echo "Decodificato: " . basename($file) . "\n";
    } else {
        echo "Fallito: " . basename($file) . "\n";
    }
}
```

### Gestire file danneggiati da OCR

[](#gestire-file-danneggiati-da-ocr)

```
use Controlaltjeff\P7MDecoder\P7MDecoder;

$xml = P7MDecoder::decodeFile('fattura-corrotta.p7m');
$corrections = P7MDecoder::getLastCorrections();

if (!empty($corrections)) {
    echo count($corrections) . " correzioni automatiche applicate:\n";
    foreach ($corrections as $fix) {
        echo "  {$fix['from']} → {$fix['to']}\n";
    }
}
```

Sviluppo
--------

[](#sviluppo)

```
git clone https://github.com/controlaltjeff/p7m-fattura-decoder.git
cd p7m-fattura-decoder
composer install
composer test       # PHPUnit (24 test)
composer stan       # PHPStan livello 8
composer fix-dry    # PHP-CS-Fixer (dry-run)
composer check      # Test + Stan + CS Fixer
```

Per mutation testing (richiede pcov o xdebug):

```
composer require --dev infection/infection:^0.29
composer mutate
```

Contribuire
-----------

[](#contribuire)

I contributi sono ben accetti! Consulta [CONTRIBUTING.md](CONTRIBUTING.md) per le linee guida.

Licenza
-------

[](#licenza)

Licenza MIT. Vedi [LICENSE](LICENSE) per i dettagli.

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance92

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

4

Last Release

40d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/20172431?v=4)[controlaltjeff](/maintainers/controlaltjeff)[@controlaltjeff](https://github.com/controlaltjeff)

---

Top Contributors

[![controlaltjeff](https://avatars.githubusercontent.com/u/20172431?v=4)](https://github.com/controlaltjeff "controlaltjeff (15 commits)")

---

Tags

fatturafattura-elettronicafattura-pafatturapafatturaxmlfatturazione-elettronicap7mpkcs7xml

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/controlaltjeff-p7m-fattura-decoder/health.svg)

```
[![Health](https://phpackages.com/badges/controlaltjeff-p7m-fattura-decoder/health.svg)](https://phpackages.com/packages/controlaltjeff-p7m-fattura-decoder)
```

###  Alternatives

[sauladam/shipment-tracker

Parses tracking information for several carriers, like UPS, USPS, DHL and GLS by simply scraping the data. No need for any kind of API access.

9843.5k](/packages/sauladam-shipment-tracker)[jstewmc/rtf

Read and write Rich Text Format (RTF) documents with PHP

45153.1k6](/packages/jstewmc-rtf)[tcds-io/php-jackson

A lightweight, flexible object serializer for PHP, inspired by FasterXML/jackson

113.2k10](/packages/tcds-io-php-jackson)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
