NER: examples in PHP with MITIE and TransformersPHP
This entry page contains two implementation variants of the same NER task: one via TransformersPHP and one via MITIE. Choose a variant below and run it separately.
Token classification pipeline with Xenova/bert-base-NER
This example uses the TransformersPHP token-classification pipeline to detect entities in text and output token-to-label pairs.
Example of code
<?php
use Codewithkyrian\Transformers\Transformers;
use function Codewithkyrian\Transformers\Pipelines\pipeline;
$text = 'Microsoft signed a contract with John Smith in London for $3 million.';
$entities = [];
$nerError = null;
try {
if (!class_exists(Transformers::class) || !function_exists('Codewithkyrian\\Transformers\\Pipelines\\pipeline')) {
throw new RuntimeException('TransformersPHP is not available. Run composer install.');
}
$pipeline = pipeline(task: 'token-classification', modelName: 'Xenova/bert-base-NER');
$entities = $pipeline($text);
} catch (Throwable $e) {
$nerError = $e->getMessage();
}
Extracting entities with Mitie\NER and local model file
This example runs NER via MITIE and prints entity text with detected tags. Runtime checks protect from missing class, FFI extension, or model file.
Example of code
<?php
use Mitie\NER;
$text = 'Apple signed a contract with John Smith in London for $3 million.';
$modelPath = '.mitie/ner_model.dat';
$entities = [];
$nerError = null;
try {
if (!class_exists(NER::class)) {
throw new RuntimeException('Class Mitie\\NER is not available. Run composer install.');
}
if (!extension_loaded('ffi')) {
throw new RuntimeException('PHP extension ffi is disabled.');
}
if (!is_file($modelPath)) {
throw new RuntimeException('MITIE model file not found: ' . $modelPath);
}
$ner = new NER($modelPath);
$entities = $ner->entities($text);
} catch (Throwable $e) {
$nerError = $e->getMessage();
}