Direct PHP National ID OCR API: Structured Data from Raw Images
Achieve 99.8% extraction accuracy and sub-1.5 second latency via a Hybrid Vision AI & MRZ Validation engine.

Why National ID OCR is Difficult
Generic OCR tools like Tesseract fail on real-world ID documents due to complexities they are not designed for. Physical cards suffer from photographic glare, shadows, and inconsistent lighting that corrupt character data. Users submit images with skew and rotation, requiring geometric correction before processing. Furthermore, simple text extraction is insufficient; data like MRZ (Machine-Readable Zone) lines contain checksums that must be algorithmically validated, not just read. Maintaining a library of RegEx patterns to parse varying ID formats across jurisdictions is a significant and brittle engineering overhead. These factors combine to make in-house ID processing a low-accuracy, high-maintenance liability.
Enterprise-Grade Extraction with StructOCR
StructOCR bypasses the fragility of open-source solutions by using pre-trained Deep Learning models specialized for identity documents. Our API doesn't just read text; it understands the structure of an ID card, offering robust id card parsing. Upon receiving an image, our system performs automatic pre-processing, including deskewing, glare removal, and denoising to normalize the input. The cleaned image is then processed by our models to extract specific fields, facilitating comprehensive information parsing, which are cross-validated and returned in a standardized JSON output. This eliminates the need for manual parsing, RegEx maintenance, and complex image processing pipelines, providing a reliable, single-step solution that consistently outperforms generic OCR engines.
Production Use Cases
- Digital Onboarding (KYC): Reduce drop-off rates by pre-filling user data from National IDs in < 2 seconds.
- Fraud Prevention: Detect tampered fonts or mismatched MRZ checksums automatically.
- Global Compliance: Handle National IDs from 200+ jurisdictions without custom rules.
Live Demo: ID card scanner
No registration required. Upload a file to test the extraction.
Drop files here or click to browse
JPG · PNG · WebP · up to 500 files · max 4.5 MB each
Implementation: Raw PHP (cURL)
The following PHP code demonstrates a complete flow using cURL. It handles image encoding, sets the required 'x-api-key' header, and parses region-specific fields (CNP, CPF, Address).
Prerequisite: PHP 7.4+ with cURL extension
<?php
// 💰 Save 30%+ vs competitors. Get 200 free credits instantly:
// 👉 https://structocr.com/register
$apiKey = 'YOUR_API_KEY_HERE';
$apiUrl = 'https://api.structocr.com/v1/national-id';
$imagePath = 'id_card.jpg'; // Supports JPG, PNG, WebP
// 1. Validate File
if (!file_exists($imagePath)) {
die("Error: File not found at $imagePath");
}
// 2. Encode Image to Base64
$imageData = file_get_contents($imagePath);
$base64Image = base64_encode($imageData);
// 3. Prepare Payload
$payload = json_encode(['img' => $base64Image]);
// 4. Initialize cURL
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-api-key: ' . $apiKey, // Required Header
'Content-Length: ' . strlen($payload)
]
]);
// 5. Execute Request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
die('cURL Error: ' . curl_error($ch));
}
curl_close($ch);
// 6. Handle Response
$result = json_decode($response, true);
if ($httpCode === 200 && isset($result['success']) && $result['success']) {
$data = $result['data'];
echo "✅ National ID Processed!\n";
echo "--------------------------\n";
echo "Region: " . ($data['country_code'] ?? 'N/A') . "\n";
echo "Name: " . ($data['given_names'] ?? '') . " " . ($data['surname'] ?? '') . "\n";
echo "Doc Number: " . ($data['document_number'] ?? 'N/A') . " (Series: " . ($data['card_series'] ?? 'N/A') . ")\n";
// Critical for verification (CNP, CPF, NIN)
echo "Personal #: " . ($data['personal_number'] ?? 'N/A') . "\n";
echo "DOB: " . ($data['date_of_birth'] ?? 'N/A') . "\n";
echo "Address: " . ($data['address'] ?? 'N/A') . "\n";
// Check and print MRZ Data if present
if (isset($data['additional_fields']['mrz_line_1'])) {
echo "MRZ Line 1: " . $data['additional_fields']['mrz_line_1'] . "\n";
if (isset($data['additional_fields']['mrz_line_2'])) {
echo "MRZ Line 2: " . $data['additional_fields']['mrz_line_2'] . "\n";
}
}
} else {
echo "❌ Processing Failed (Status $httpCode)\n";
if (isset($result['error'])) {
echo "Error: " . $result['error'] . "\n";
} else {
echo $response;
}
}
?>Technical Specs
- •Latency: < 4s (Average)
- •Uptime: 99.9% SLA
- •Security: AES-256 Encryption & SOC2 Compliant
- •Input: JPG, PNG, WebP (Base64 Encoded)
- •Max File Size: 4.5MB
- •Output: JSON (Structured Data)
Key Features
- •Hybrid VIZ + MRZ AI: Cross-validates unstructured visual data against cryptographic MRZ checksums (TD1/TD2) for zero hallucination.
- •Specialized Numbers: Extracts region-specific IDs like CNP (Romania), CPF (Brazil), and NIN (Nigeria).
- •Multi-line Addresses: Intelligently reconstructs full addresses from fragmented lines on ID cards.
Sample JSON Output
StructOCR returns a normalized JSON object containing both Visual Zone (VIZ) extraction and raw Machine-Readable Zone (MRZ) lines.
{
"success": true,
"data": {
"type": "national_id",
"country_code": "ROU",
"nationality": "ROMANA",
"document_number": "123456",
"card_series": "KS",
"personal_number": "1920319123456",
"surname": "POPESCU",
"given_names": "ANDREI",
"sex": "M",
"date_of_birth": "1992-03-19",
"place_of_birth": "Jud. CS Mun. Reșița",
"address": "Jud. CS Orș. Bocșa Str. Nucilor Nr. 15",
"date_of_issue": "2020-05-10",
"date_of_expiry": "2030-05-10",
"issuing_authority": "SPCLEP Bocșa",
"additional_fields": {
"phone_number": null,
"tramite_number": null,
"ejemplar": null,
"mrz_line_1": "IDROU123456<0<<<<<<<<<<<<<<<<",
"mrz_line_2": "9203195M3005108ROU19203191234562",
"mrz_line_3": null
}
}
}Frequently Asked Questions
Do you support Machine Readable Zones (MRZ) on ID cards?
Yes! Our engine natively supports ICAO 9303 standard MRZ formats (TD1/TD2) found on many global ID cards. Our Hybrid architecture extracts both the raw MRZ lines and cross-validates them against the Visual Zone (VIZ) for maximum accuracy.
How does StructOCR compare to AWS Textract or Google Vision?
General-purpose OCR services like Textract or Vision return raw lines of text and their coordinates. You are still responsible for parsing, validating, and structuring that data. StructOCR is a specialized, vertical solution that performs these steps for you, returning a clean JSON object with labeled fields like `surname` and `date_of_birth` directly.
Do you store the uploaded images?
No. Images are processed entirely in-memory and are permanently deleted immediately after the extraction request is completed. We do not persist sensitive customer data on our servers.
How do you handle blurry or low-quality images?
Our API pipeline includes an automatic image enhancement engine that applies denoising, deblurring, and contrast correction before analysis. This significantly improves extraction accuracy on sub-optimal images captured by mobile devices.
You May Also Like
Related tutorials, platform guides, and comparisons
Tanzania NIDA Card OCR Python SDK
Python Tutorial: Automate KYC in Tanzania. Extract data from NIDA Card using StructOCR Python SDK. Supports native text and MRZ extraction.
Saudi Arabia National ID & Iqama OCR Python SDK
Python Tutorial: Automate KYC in Saudi Arabia. Extract data from National IDs and Iqamas using the StructOCR Python SDK. Supports bilingual (Arabic/English) text, 10-digit ID numbers, and 3-line MRZ extraction.
France Carte Nationale d'Identité OCR Python SDK
Python Tutorial: Automate KYC in France. Extract data from Carte Nationale d'Identité and validate TD1/TD2 MRZ using StructOCR Python SDK. Supports native text.
Go National ID OCR API
Upload an image for a free test! High-accuracy National ID data extraction for Go developers. Get structured JSON output via a simple API call, replacing unreliable open-source tools.
Indonesia KTP OCR with Node.js SDK
Extract NIK, names, dates and other visible fields from Kartu Tanda Penduduk (KTP) with the StructOCR Node.js SDK and Express.
Philippines PhilID OCR with Node.js SDK
Extract PhilSys Card Number, names, dates and other visible fields from Philippine Identification Card (PhilID) with the StructOCR Node.js SDK and Express.
UAE Emirates ID OCR with Node.js SDK
Extract Emirates ID number, names, dates and other visible fields from Emirates ID with the StructOCR Node.js SDK and Express.
Python National ID OCR API
High-accuracy National ID OCR for Python. Upload an image for a free test! Get structured JSON output via our dedicated Python SDK. Automate KYC and data entry with 99%+ accuracy.
Tunisia CIN (Carte d'Identité Nationale) OCR Python SDK
Python Tutorial: Automate KYC in Tunisia. Extract data from CIN (Carte d'Identité Nationale) using StructOCR Python SDK. Supports native text.
South Africa Smart ID OCR with Node.js SDK
Extract identity number, names, dates and other visible fields from South African Smart ID card with the StructOCR Node.js SDK and Express.
Technical Comparisons & Integrations
Explore platform integrations and competitive analysis
Add National ID OCR to Your Bolt.new App in 5 Minutes
Step-by-step guide to integrating the StructOCR National ID scanner API into a Bolt.new app. Build KYC and identity verification flows right in your browser.
Add National ID OCR using Cursor in 5 Minutes
Step-by-step guide to integrating the StructOCR National ID scanner API using the Cursor AI code editor. Build KYC and identity verification flows rapidly.
Add National ID OCR to Your Lovable.dev App in 5 Minutes
Step-by-step guide to integrating the StructOCR National ID scanner API into a Lovable.dev app. Build KYC and identity verification flows with zero backend.
Add National ID OCR to Your Replit App in 5 Minutes
Step-by-step guide to integrating the StructOCR National ID scanner API into a Replit application. Build KYC and identity verification flows using Replit Agent and Secrets.
Add National ID OCR to Your v0 App in 5 Minutes
Step-by-step guide to integrating the StructOCR National ID scanner API into a v0 by Vercel app. Build KYC and identity verification flows with zero backend.
Add Receipt OCR using Cursor in 5 Minutes
Step-by-step guide to integrating the StructOCR receipt API using the Cursor AI code editor. Build expense tracking and receipt scanning tools rapidly.
From tutorial to production in 5 minutes.
You've seen the code. Now get your API key, grab your 200 free credits, and see it work with your own images. No credit card required.