Symfony: Turn Website Lists into Researchable Company Profiles with AI Data Extraction
A spreadsheet of company websites looks like a prospect list until someone has to open every page, identify the business, find contact details, and explain where each result came from. The expensive part is turning scattered information into something another person can review.
This Symfony project converts a CSV of company homepages into a contact-research CSV using Website to Company data. It preserves website provenance, separates extraction failures from reviewable results, and leaves outreach decisions to a person.
Get access and copy the service token
- Register an account or sign in.
- Open the Website to Company data service and plan page.
- Choose the available Free, Plus, or Pro plan and complete activation.
- Open the official service documentation, find the Service token panel, and copy the service-scoped token.
This service requires a token. Regenerating it revokes the previous active token, so coordinate rotation with any running integrations.
The request is exactly GET https://ai.mihajlo.mk/api/website-to-company-data/v1/extract, with token and website query parameters. Test from a private terminal, replacing both placeholders:
curl --get --fail-with-body \
--connect-timeout 5 --max-time 25 \
'https://ai.mihajlo.mk/api/website-to-company-data/v1/extract' \
--data-urlencode 'token=YOUR_SERVICE_TOKEN' \
--data-urlencode 'website=https://example.com'
Use an actual company homepage for a meaningful result. Inspect its response alongside the documentation before processing a list. Avoid shared terminals and HTTP tracing: query authentication makes the complete request URL sensitive.
Create a small, bounded Symfony application
Use PHP 8.3 or newer, Composer, and Symfony 7.4. A synchronous console command suits a small team processing occasional batches. A limit of 100 unique websites and sequential requests keep resource use predictable; Messenger would add little value here.
composer create-project symfony/skeleton:"7.4.*" company-research
cd company-research
composer require symfony/console symfony/http-client
composer require --dev phpunit/phpunit:"^11.5"
Before implementing the feature, put the token in the project's untracked .env.local:
WEBSITE_COMPANY_TOKEN=YOUR_SERVICE_TOKEN
Keep a placeholder in any committed environment example. Production should supply the variable through its secret manager or protected environment configuration.
The application adds three files: src/Research/Extractor.php, src/Command/ResearchCommand.php, and tests/ExtractorTest.php. Replace config/services.yaml with:
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/'
exclude: '../src/Kernel.php'
App\Research\Extractor:
arguments:
$serviceToken: '%env(WEBSITE_COMPANY_TOKEN)%'
Make the API boundary responsible for uncertainty
The supplied contract identifies company, contact, email, phone, and people data without defining their nested schemas. The adapter below accepts those category keys at the response root and preserves their values as JSON. It does not invent person properties, flatten multiple contacts into one, or infer missing addresses.
Missing categories remain blank and are named in a separate column. A response containing none of the recognized categories becomes schema_error. If your documented response uses an envelope, change this boundary against that documented structure before deployment.
Create src/Research/Extractor.php:
<?php
namespace App\Research;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final class Extractor
{
private const KEYS = ['company', 'contact', 'email', 'phone', 'people'];
public function __construct(
private HttpClientInterface $http,
private string $serviceToken,
) {}
public function extract(string $website): array
{
$empty = [
'fields' => array_fill_keys(self::KEYS, ''),
'missing' => '',
];
for ($attempt = 1; $attempt <= 3; ++$attempt) {
try {
$response = $this->http->request('GET',
'https://ai.mihajlo.mk/api/website-to-company-data/v1/extract',
[
'query' => [
'token' => $this->serviceToken,
'website' => $website,
],
'timeout' => 5,
'max_duration' => 20,
'max_redirects' => 0,
]
);
$status = $response->getStatusCode();
if ($status === 200) {
$body = $response->getContent(false);
try {
$data = json_decode($body, false, 64, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return ['state' => 'invalid_response', ...$empty];
}
return $this->map($data, $empty);
}
$response->cancel();
if (in_array($status, [502, 503, 504], true)) {
if ($attempt < 3) {
sleep($attempt);
continue;
}
return ['state' => 'upstream_error', ...$empty];
}
$state = match ($status) {
401, 403 => 'auth_error',
429 => 'quota_deferred',
400, 422 => 'rejected',
default => 'http_error',
};
return ['state' => $state, ...$empty];
} catch (TransportExceptionInterface) {
if ($attempt === 3) {
return ['state' => 'transport_error', ...$empty];
}
sleep($attempt);
}
}
throw new \LogicException('Unreachable retry state');
}
private function map(mixed $data, array $empty): array
{
if (!$data instanceof \stdClass) {
return ['state' => 'schema_error', ...$empty];
}
$fields = $empty['fields'];
$missing = [];
foreach (self::KEYS as $key) {
if (!property_exists($data, $key) || $data->$key === null) {
$missing[] = $key;
continue;
}
$fields[$key] = json_encode(
$data->$key,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE
);
}
return [
'state' => count($missing) === count(self::KEYS)
? 'schema_error' : 'review',
'fields' => $fields,
'missing' => implode(',', $missing),
];
}
}
The five-second inactivity timeout covers connection establishment and stalled reads; the twenty-second duration limit bounds each attempt overall. Retries wait one, then two seconds. Authentication and validation failures are never retried. A 429 stops further API calls for the batch; resume only after checking quota and any provider retry guidance.
Even GET retries can consume quota or repeat upstream work. These three attempts are a deliberate ceiling, not a promise of exactly-once processing. Raw transport exceptions are discarded because their messages can contain the credential-bearing URL.
Build the review-list command
Export the spreadsheet as UTF-8 CSV with one column headed website. This implementation accepts ASCII HTTP or HTTPS homepages, rejects paths and credentials, validates the entire input before making requests, and deduplicates normalized addresses.
Create src/Command/ResearchCommand.php:
<?php
namespace App\Command;
use App\Research\Extractor;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:research')]
final class ResearchCommand extends Command
{
public function __construct(private Extractor $extractor)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('input', InputArgument::REQUIRED);
$this->addArgument('output', InputArgument::REQUIRED);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$in = fopen($input->getArgument('input'), 'rb');
if ($in === false) {
throw new \RuntimeException('Cannot open input');
}
$sites = [];
try {
if (fgetcsv($in, 0, ',', '"', '') !== ['website']) {
throw new \InvalidArgumentException('Expected website header');
}
while (($row = fgetcsv($in, 0, ',', '"', '')) !== false) {
if (count($row) !== 1) {
throw new \InvalidArgumentException('Expected one column');
}
$url = trim($row[0] ?? '');
$parts = parse_url($url);
$host = strtolower($parts['host'] ?? '');
if (!is_array($parts)
|| !in_array($parts['scheme'] ?? '', ['http', 'https'], true)
|| !str_contains($host, '.')
|| !filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)
|| filter_var($host, FILTER_VALIDATE_IP)
|| isset($parts['user'], $parts['pass'])
|| isset($parts['user'])
|| isset($parts['port'])
|| isset($parts['query'])
|| isset($parts['fragment'])
|| !in_array($parts['path'] ?? '', ['', '/'], true)
) {
throw new \InvalidArgumentException('Invalid company homepage');
}
$sites[$parts['scheme'].'://'.$host] = true;
if (count($sites) > 100) {
throw new \InvalidArgumentException('Maximum 100 unique websites');
}
}
} finally {
fclose($in);
}
$out = fopen($input->getArgument('output'), 'x');
if ($out === false) {
throw new \RuntimeException('Output must be a new writable file');
}
$failed = false;
$blocked = false;
try {
$this->write($out, [
'website', 'state', 'retrieved_at', 'company', 'contact',
'email', 'phone', 'people', 'missing',
]);
foreach (array_keys($sites) as $index => $website) {
$result = $blocked
? ['state' => 'deferred', 'fields' => [], 'missing' => '']
: $this->extractor->extract($website);
$state = $result['state'];
$failed = $failed || $state !== 'review';
$blocked = $blocked || in_array(
$state, ['auth_error', 'quota_deferred'], true
);
$fields = $result['fields'];
$this->write($out, [
$website, $state,
$state === 'review' ? gmdate('c') : '',
$fields['company'] ?? '', $fields['contact'] ?? '',
$fields['email'] ?? '', $fields['phone'] ?? '',
$fields['people'] ?? '', $result['missing'],
]);
$output->writeln(json_encode([
'row' => $index + 1, 'state' => $state,
], JSON_THROW_ON_ERROR));
}
} finally {
fclose($out);
}
return $failed ? Command::FAILURE : Command::SUCCESS;
}
private function write($stream, array $cells): void
{
$cells = array_map(static function (string $cell): string {
return preg_match('/^[\x00-\x20=+\-@]/', $cell)
? "'".$cell : $cell;
}, $cells);
if (fputcsv($stream, $cells, ',', '"', '') === false
|| !fflush($stream)) {
throw new \RuntimeException('Cannot persist output');
}
}
}
The output is created exclusively, preventing accidental replacement of earlier research. Every completed row is flushed, so an interrupted process leaves a readable partial file. Flushing is not a guarantee against storage or power failure.
After interruption, compare normalized website values and prepare a new input containing only unfinished or failed rows. Automatic resume would require durable state; silently replaying the original input could spend quota twice.
Formula-sensitive CSV cells receive a leading apostrophe. JSON preserves the distinction between strings, lists, and objects, although spreadsheet import settings still deserve verification. A review row means extraction succeeded, not that an address belongs to a decision-maker or has permission for outreach.
Test the contract without contacting the service
Create tests/ExtractorTest.php. These fixtures describe the adapter's accepted shape; they are not claimed samples of the provider's complete schema.
<?php
use App\Research\Extractor;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
final class ExtractorTest extends TestCase
{
public function testMappingAndRequest(): void
{
$http = new MockHttpClient(function ($method, $url, $options) {
self::assertSame('GET', $method);
self::assertSame(
'https://ai.mihajlo.mk/api/website-to-company-data/v1/extract',
strtok($url, '?')
);
parse_str(parse_url($url, PHP_URL_QUERY), $query);
self::assertSame('fixture-token', $query['token']);
self::assertSame('https://example.com', $query['website']);
self::assertSame(0, $options['max_redirects']);
return new MockResponse(
'{"company":"Example","email":["[email protected]"]}'
);
});
$result = (new Extractor($http, 'fixture-token'))
->extract('https://example.com');
self::assertSame('review', $result['state']);
self::assertSame('["[email protected]"]', $result['fields']['email']);
self::assertSame('contact,phone,people', $result['missing']);
}
public function testAuthenticationAndQuotaAreNotRetried(): void
{
foreach ([401 => 'auth_error', 429 => 'quota_deferred'] as $code => $state) {
$http = new MockHttpClient([
new MockResponse('', ['http_code' => $code]),
]);
self::assertSame($state, (new Extractor($http, 'fixture-token'))
->extract('https://example.com')['state']);
self::assertSame(1, $http->getRequestsCount());
}
}
public function testTransientFailureCanRecover(): void
{
$http = new MockHttpClient([
new MockResponse('', ['http_code' => 503]),
new MockResponse('{"company":"Example"}'),
]);
self::assertSame('review', (new Extractor($http, 'fixture-token'))
->extract('https://example.com')['state']);
self::assertSame(2, $http->getRequestsCount());
}
public function testUnknownShapeFailsClosed(): void
{
$http = new MockHttpClient(new MockResponse('[]'));
self::assertSame('schema_error', (new Extractor($http, 'fixture-token'))
->extract('https://example.com')['state']);
}
}
vendor/bin/phpunit --bootstrap vendor/autoload.php tests
php bin/console lint:container
php bin/console app:research websites.csv research.csv
Deploy with visible, recoverable failure states
Deploy the lockfile with composer install --no-dev --optimize-autoloader, set APP_ENV=prod and APP_DEBUG=0, inject the token, and warm the cache with php bin/console cache:warmup. Keep input and output outside the public directory with permissions restricted to the operator.
Allow roughly 105 minutes for the worst-case 100-site run: each site can take three twenty-second attempts plus backoff. Prevent overlapping scheduled runs, use unique output filenames, and treat a nonzero exit code as requiring review.
Structured console records contain row numbers and states, never tokens or response bodies. Count failures by state and monitor execution time. Disable or redact outbound URL capture in profilers and monitoring agents, including the initial request used during setup.
An authentication failure usually calls for checking activation, environment loading, or token rotation. Quota deferral calls for checking the plan and retry guidance. Invalid responses and schema errors require comparing the actual response with the documented contract. Do not repeatedly rerun them hoping that different data will appear.
Verify the list before anyone uses it
- Confirm tests and container validation pass before deployment.
- Run one real company through the activated service and compare its mapped categories with the documented response.
- Open the CSV in the team's spreadsheet application and verify JSON cells, quoting, and missing-category indicators.
- Confirm failed and deferred rows remain visible and produce a nonzero command exit.
- Check application and infrastructure logs for credential-bearing URLs.
- Review contact relevance, provenance, and applicable privacy obligations before outreach.
The useful deliverable is a research list that explains its own limits. When every row retains its source, every missing category stays visible, and every failed request has a recoverable state, AI extraction becomes a dependable starting point for human judgment.