惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog
C
Check Point Blog
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
SecWiki News
SecWiki News
有赞技术团队
有赞技术团队
Latest news
Latest news
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
Project Zero
Project Zero
H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
T
Threat Research - Cisco Blogs
腾讯CDC
P
Proofpoint News Feed
L
LINUX DO - 热门话题
C
Cisco Blogs
P
Palo Alto Networks Blog
Vercel News
Vercel News
P
Privacy International News Feed
爱范儿
爱范儿
Scott Helme
Scott Helme
L
Lohrmann on Cybersecurity
MyScale Blog
MyScale Blog
K
Kaspersky official blog
B
Blog RSS Feed
美团技术团队
Microsoft Security Blog
Microsoft Security Blog
O
OpenAI News
博客园 - 叶小钗
量子位
T
Tenable Blog
C
Cybersecurity and Infrastructure Security Agency CISA
J
Java Code Geeks
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LINUX DO - 最新话题
F
Fortinet All Blogs
N
News | PayPal Newsroom
The Hacker News
The Hacker News
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - 【当耐特】
N
News and Events Feed by Topic
V
Visual Studio Blog
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Bilingual FR/EN blog in pure PHP: architecture without framework or database
Odilon HUGON · 2026-05-12 · via DEV Community

This blog was built in pure PHP, no CMS, no database. First article in the series, already published. At some point the question comes up: is it worth adding English support? Short answer: yes, and it's less complicated than it looks. Long answer: here's how I did it, with the traps that come with it.

No gettext, no i18n library, no database for translations. Just separate PHP files per language, a restructured JSON file, and three layers of routing. The whole thing fits in a few dozen lines of code spread across files you already have.

Why translate a developer blog

Two concrete reasons, no philosophy.

The English-speaking SEO market is 10 to 50 times larger. A query like "php blog without framework" has a search volume that has nothing to do with the French equivalent. If you write about technical topics that interest English-speaking developers — and you probably do if you're reading this — not having an EN version means missing an existing audience without the overhead being that large once the architecture is in place.

It shows recruiters you're bilingual. A portfolio available in English, with properly written technical content, is a strong signal. No need to mention it in your CV — the site speaks for itself. An international recruiter who lands on your article via Google EN immediately sees that you can work in English.

There's a third reason that's not easy to admit but real: writing the same article in two languages forces you to restructure explanations. It often improves the original version in the process.

Architecture decisions

URL structure

The main constraint: don't break existing URLs. All already-published articles live at /blog/slug. These URLs don't move. English versions live at /en/blog/slug.

/blog/blog-multilingue-php-sans-framework      # FR (default)
/en/blog/blog-multilingue-php-sans-framework   # EN

Enter fullscreen mode Exit fullscreen mode

The /en/ prefix is simple to detect, to generate in links, and to route server-side. No ?lang=en parameter, no cookie, no automatic browser language detection — the URL is the source of truth. This is the only model that works correctly for SEO (search engines index distinct URLs) and respects the principle of least surprise for the user.

One PHP file per language

For each article, two files:

blog/posts/
├── my-slug.php       # French version
└── my-slug.en.php    # English version

Enter fullscreen mode Exit fullscreen mode

The alternative — a single file with translation arrays — looks like this in real life:

<?php
$texts = [
    'fr' => [
        'intro' => 'Ce blog a été construit en PHP pur...',
        'section1' => 'Les choix d\'architecture...',
        // 800 lines of content inside quotes with escaping everywhere
    ],
    'en' => [
        'intro' => 'This blog was built in pure PHP...',
        // 800 more lines
    ],
];
echo $texts[$lang]['intro'];

Enter fullscreen mode Exit fullscreen mode

It's unreadable, unmaintainable, and you spend half your time managing apostrophes and quotes. One file per language is more verbose in terms of file count, but each file is simple to read and modify independently. That's the right trade-off for a blog.

Bonus: if an article doesn't have an English version, the .en.php file simply doesn't exist. The router returns a clean 404. No complex fallback logic needed.

Restructured posts.json

Before adding multilingual support, the JSON was flat:

{
  "slug": "my-slug",
  "date": "2026-03-15",
  "title": "Article title",
  "category": "Lessons learned",
  "tags": ["php", "blog"],
  "excerpt": "Short summary."
}

Enter fullscreen mode Exit fullscreen mode

After migration, language-dependent fields are nested inside fr and en objects:

{
  "slug": "my-slug",
  "date": "2026-03-15",
  "fr": {
    "title": "Titre de l'article",
    "category": "Retour d'expérience",
    "tags": ["php", "blog"],
    "excerpt": "Résumé court."
  },
  "en": {
    "title": "Article title",
    "category": "Lessons learned",
    "tags": ["php", "blog"],
    "excerpt": "Short summary."
  }
}

Enter fullscreen mode Exit fullscreen mode

The date stays at root level — it's language-independent. So is the slug — it's the same for both versions.

Migrating existing data is done with a one-shot PHP script (see below). Don't do it by hand for 30+ articles.

template.php receives $lang

The blog_header() signature already had a $lang parameter set up but unused. It becomes functional:

<?php
function blog_header(
    string $title,
    string $description,
    string $canonical_url,
    ?string $og_image = null,
    ?array $article_data = null,
    string $lang = 'fr'
): void {

Enter fullscreen mode Exit fullscreen mode

This parameter drives: the lang attribute on <html>, og:locale, hreflang tags, breadcrumbs, navigation, and the language toggle. One parameter, no global variable.

The three routing layers

The routing architecture is the trickiest part. It has three layers that must stay consistent with each other, otherwise you end up with a site that works in production but not in development, or vice versa.

Layer 1: .htaccess for Apache

The clean FR blog URLs already existed in .htaccess. The EN addition comes down to two lines:

# Blog EN: /en/blog/slug → blog/posts/slug.en.php
RewriteRule ^en/blog/([a-z0-9-]+)/?$ blog/posts/$1.en.php [L,QSA]

# Blog listing EN: /en/blog/ → blog/index.php with lang=en
RewriteRule ^en/blog/?$ blog/index.php?lang=en [L,QSA]

Enter fullscreen mode Exit fullscreen mode

Two rules. That's it. The existing routing already handles FR URLs. The EN article rule must be added before the FR rules to avoid pattern conflicts — Apache rules apply in declaration order.

Layer 2: router.php for the built-in PHP server

The built-in PHP server (php -S localhost:8000 router.php) doesn't execute .htaccess files. The router.php simulates the same rewrites:

<?php
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = rtrim($uri, '/');

// EN blog articles
if (preg_match('#^/en/blog/([a-z0-9-]+)$#', $uri, $m)) {
    $file = __DIR__ . '/blog/posts/' . $m[1] . '.en.php';
    if (file_exists($file)) {
        require $file;
        return true;
    }
    // Fallback 404
    http_response_code(404);
    require __DIR__ . '/404.php';
    return true;
}

// EN blog listing
if ($uri === '/en/blog') {
    $_GET['lang'] = 'en';
    require __DIR__ . '/blog/index.php';
    return true;
}

Enter fullscreen mode Exit fullscreen mode

The structure is identical to the Apache logic, translated to PHP. The classic trap here: forgetting to set $_GET['lang'] = 'en' before including index.php. If you test locally and the EN listing displays FR articles, that's where the bug lives.

Layer 3: detection in template.php

The template can receive $lang as a parameter (from articles), but it can also detect the language from the URL (for dynamic pages that don't go through blog_header()):

<?php
// Language detection from URL (fallback if $lang not provided)
function detect_lang(): string {
    $uri = $_SERVER['REQUEST_URI'] ?? '';
    return str_starts_with($uri, '/en/') ? 'en' : 'fr';
}

Enter fullscreen mode Exit fullscreen mode

In practice, articles always pass $lang explicitly. Automatic detection primarily serves the listing and pages that don't have article context.

Template changes

html lang and og:locale

The most visible and simplest change:

<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
    ...
    <meta property="og:locale" content="<?= $lang === 'en' ? 'en_US' : 'fr_FR' ?>">

Enter fullscreen mode Exit fullscreen mode

hreflang tags

The hreflang tags tell search engines about alternative versions of a page. They go in the <head> and are generated from the article slug:

<?php if (!empty($article_data['slug'])): ?>
<link rel="alternate" hreflang="fr"
      href="<?= SITE_URL ?>/blog/<?= $article_data['slug'] ?>">
<link rel="alternate" hreflang="en"
      href="<?= SITE_URL ?>/en/blog/<?= $article_data['slug'] ?>">
<link rel="alternate" hreflang="x-default"
      href="<?= SITE_URL ?>/blog/<?= $article_data['slug'] ?>">
<?php endif; ?>

Enter fullscreen mode Exit fullscreen mode

x-default points to the FR version — that's the site's default language. If a user arrives from a country without a localized version, they see FR. Google uses x-default for pages not geographically targeted.

Important: these tags must be reciprocal. The FR page must point to the EN page, and the EN page must point to the FR page. If you miss one direction, Google ignores both.

Adapted breadcrumbs

The breadcrumb changes depending on language — not just the text, but also the URLs:

<?php
$home_url   = $lang === 'en' ? SITE_URL . '/en' : SITE_URL;
$blog_url   = $lang === 'en' ? SITE_URL . '/en/blog' : SITE_URL . '/blog';
$home_label = $lang === 'en' ? 'Home' : 'Accueil';
$blog_label = 'Blog';
?>
<ol class="breadcrumb">
    <li><a href="<?= $home_url ?>"><?= $home_label ?></a></li>
    <li><a href="<?= $blog_url ?>"><?= $blog_label ?></a></li>
    <li class="active"><?= htmlspecialchars($title) ?></li>
</ol>

Enter fullscreen mode Exit fullscreen mode

Language toggle with SVG flags

The navigation toggle shows the flag for the target language (not the current language — the other one). This avoids the paradox of "FR" displayed on a page already in French.

<?php
$toggle_url  = $lang === 'fr'
    ? SITE_URL . '/en/blog/' . ($article_data['slug'] ?? '')
    : SITE_URL . '/blog/'    . ($article_data['slug'] ?? '');
$toggle_lang = $lang === 'fr' ? 'EN' : 'FR';
$toggle_flag = $lang === 'fr' ? '🇬🇧' : '🇫🇷';
// Or SVG inline if emoji rendering is inconsistent
?>
<a href="<?= htmlspecialchars($toggle_url) ?>" class="lang-toggle"
   title="<?= $lang === 'fr' ? 'Read in English' : 'Lire en français' ?>">
    <?= $toggle_flag ?> <?= $toggle_lang ?>
</a>

Enter fullscreen mode Exit fullscreen mode

If you prefer inline SVGs instead of emoji (more reliable on older OS/browsers), here's a compact example:

<?php if ($lang === 'fr'): ?>
<a href="<?= $toggle_url ?>" class="lang-toggle" title="Read in English">
    <svg width="18" height="12" viewBox="0 0 60 40" xmlns="http://www.w3.org/2000/svg">
        <rect width="60" height="40" fill="#012169"/>
        <path d="M0,0 L60,40 M60,0 L0,40" stroke="#fff" stroke-width="8"/>
        <path d="M0,0 L60,40 M60,0 L0,40" stroke="#C8102E" stroke-width="5"/>
        <path d="M30,0 V40 M0,20 H60" stroke="#fff" stroke-width="12"/>
        <path d="M30,0 V40 M0,20 H60" stroke="#C8102E" stroke-width="8"/>
    </svg>
    EN
</a>
<?php else: ?>
<a href="<?= $toggle_url ?>" class="lang-toggle" title="Lire en français">
    <svg width="18" height="12" viewBox="0 0 90 60" xmlns="http://www.w3.org/2000/svg">
        <rect width="30" height="60" fill="#002395"/>
        <rect x="30" width="30" height="60" fill="#EDEDED"/>
        <rect x="60" width="30" height="60" fill="#ED2939"/>
    </svg>
    FR
</a>
<?php endif; ?>

Enter fullscreen mode Exit fullscreen mode

Migrating posts.json: the one-shot script

If you have existing articles with the flat structure, here's the migration script. Run it once from the project root:

<?php
// migrate-posts.php — delete after use
$json = file_get_contents('blog/posts.json');
$posts = json_decode($json, true);

$migrated = [];
foreach ($posts as $post) {
    // Already migrated?
    if (isset($post['fr'])) {
        $migrated[] = $post;
        continue;
    }

    $migrated[] = [
        'slug' => $post['slug'],
        'date' => $post['date'],
        'fr'   => [
            'title'    => $post['title'],
            'category' => $post['category'],
            'tags'     => $post['tags'],
            'excerpt'  => $post['excerpt'],
        ],
        'en'   => [
            'title'    => $post['title'],    // Translate manually
            'category' => $post['category'], // idem
            'tags'     => $post['tags'],
            'excerpt'  => $post['excerpt'],  // idem
        ],
    ];
}

file_put_contents(
    'blog/posts.json',
    json_encode($migrated, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
echo count($migrated) . " articles migrated.\n";

Enter fullscreen mode Exit fullscreen mode

The script copies FR fields into EN as placeholders. You then rework the EN fields manually. Don't forget to delete migrate-posts.php after you're done — it's not an endpoint you want exposed in production.

Blog listing (index.php)

The listing reads posts.json in JavaScript and filters articles by current language. Two main changes.

Reading the current language

// Determine language from URL
const BLOG_LANG = window.location.pathname.startsWith('/en/') ? 'en' : 'fr';

Enter fullscreen mode Exit fullscreen mode

Fetch with absolute path

This is the most common trap. Using a relative path to fetch posts.json:

// ❌ Relative path — PROBLEM on /en/blog/
fetch('posts.json')
  .then(r => r.json())

Enter fullscreen mode Exit fullscreen mode

On /blog/, this fetch resolves to /blog/posts.json — correct. But on /en/blog/, it resolves to /en/blog/posts.json — 404. The file only exists in one place.

// ✅ Absolute path — works from any URL
fetch('/blog/posts.json')
  .then(r => r.json())
  .then(posts => renderPosts(posts, BLOG_LANG));

Enter fullscreen mode Exit fullscreen mode

This was the first bug I hit after deploying the EN listing. Everything worked locally (router.php serves from the root, so relative paths happened to resolve correctly), but broke immediately on the real URL structure. Absolute paths are the only correct answer here.

Language filter in JS

function renderPosts(posts, lang) {
    // Filter articles that have a version in this language
    const filtered = posts.filter(post => post[lang] && post[lang].title);

    filtered.forEach(post => {
        const data = post[lang];
        const url  = lang === 'en'
            ? `/en/blog/${post.slug}`
            : `/blog/${post.slug}`;

        // Build card with data.title, data.excerpt, data.category, data.tags
        renderCard({ ...data, slug: post.slug, date: post.date, url });
    });
}

Enter fullscreen mode Exit fullscreen mode

This means an article without an EN version simply doesn't appear in the EN listing. That's the correct behaviour — it's not a missing feature, it's the expected result of having a .en.php file as the gating condition.

Category filter translation

Category filter buttons change label depending on language. The FR → EN mapping is a simple constant:

// Categories are read dynamically from posts.json
// The labels come from the nested lang object, so no mapping needed:
// post.fr.category = "Retour d'expérience"
// post.en.category = "Lessons learned"
// They're already translated at the data level.

const categories = [...new Set(
    posts
        .filter(p => p[BLOG_LANG])
        .map(p => p[BLOG_LANG].category)
)].sort();

// Dynamically build filter buttons — no hardcoded list
categories.forEach(cat => {
    const btn = document.createElement('button');
    btn.className = 'btn-category';
    btn.dataset.category = cat;
    btn.textContent = cat;
    filterContainer.appendChild(btn);
});

Enter fullscreen mode Exit fullscreen mode

Because category names are stored in posts.json per language, the buttons are already translated at the data level. No extra mapping layer needed.

Sitemap with hreflang

The XML sitemap must declare alternative URLs for each bilingual page. The xhtml namespace is required for xhtml:link tags:

<?php
$posts = json_decode(file_get_contents(__DIR__ . '/posts.json'), true);
header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">
<?php foreach ($posts as $post): ?>
    <?php if (!empty($post['fr'])): ?>
    <url>
        <loc><?= SITE_URL ?>/blog/<?= $post['slug'] ?></loc>
        <lastmod><?= $post['date'] ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.8</priority>
        <xhtml:link rel="alternate" hreflang="fr"
                    href="<?= SITE_URL ?>/blog/<?= $post['slug'] ?>"/>
        <?php if (!empty($post['en'])): ?>
        <xhtml:link rel="alternate" hreflang="en"
                    href="<?= SITE_URL ?>/en/blog/<?= $post['slug'] ?>"/>
        <xhtml:link rel="alternate" hreflang="x-default"
                    href="<?= SITE_URL ?>/blog/<?= $post['slug'] ?>"/>
        <?php endif; ?>
    </url>
    <?php endif; ?>
    <?php if (!empty($post['en'])): ?>
    <url>
        <loc><?= SITE_URL ?>/en/blog/<?= $post['slug'] ?></loc>
        <lastmod><?= $post['date'] ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
        <xhtml:link rel="alternate" hreflang="fr"
                    href="<?= SITE_URL ?>/blog/<?= $post['slug'] ?>"/>
        <xhtml:link rel="alternate" hreflang="en"
                    href="<?= SITE_URL ?>/en/blog/<?= $post['slug'] ?>"/>
        <xhtml:link rel="alternate" hreflang="x-default"
                    href="<?= SITE_URL ?>/blog/<?= $post['slug'] ?>"/>
    </url>
    <?php endif; ?>
<?php endforeach; ?>
</urlset>

Enter fullscreen mode Exit fullscreen mode

EN article priority (0.7) is slightly lower than FR articles (0.8) — the site defaults to French, FR articles are the source of truth. It's a convention, not a strict rule.

Related articles filtered by language

The "related articles" section at the bottom of a post must link to articles in the same language. If you're reading an EN article and the suggestions point to FR URLs, that's a bad experience.

The existing similarity calculation (see the dedicated article) is extended to filter by language before scoring:

<?php
function get_related_posts(
    string $current_slug,
    array $current_tags,
    string $current_category,
    string $lang = 'fr',
    int $limit = 3
): array {
    $posts = json_decode(file_get_contents(__DIR__ . '/../posts.json'), true);
    $scores = [];

    foreach ($posts as $post) {
        if ($post['slug'] === $current_slug) continue;

        // Filter: article must exist in the target language
        if (empty($post[$lang])) continue;

        $data  = $post[$lang];
        $score = 0;

        // Score by category
        if ($data['category'] === $current_category) $score += 3;

        // Score by shared tags
        $common = array_intersect($data['tags'] ?? [], $current_tags);
        $score += count($common) * 2;

        if ($score > 0) {
            $url = $lang === 'en'
                ? '/en/blog/' . $post['slug']
                : '/blog/'    . $post['slug'];

            $scores[] = [
                'url'   => $url,
                'title' => $data['title'],
                'score' => $score,
            ];
        }
    }

    usort($scores, fn($a, $b) => $b['score'] - $a['score']);

    return array_slice(
        array_map(fn($s) => ['url' => $s['url'], 'title' => $s['title']], $scores),
        0,
        $limit
    );
}

Enter fullscreen mode Exit fullscreen mode

Called from article files:

<?php
// In my-slug.php (FR)
blog_footer(
    get_related_posts('my-slug', ['php', 'blog'], 'Retour d\'expérience', 'fr'),
    'my-slug',
    'fr'
);

// In my-slug.en.php (EN)
blog_footer(
    get_related_posts('my-slug', ['php', 'blog'], 'Lessons learned', 'en'),
    'my-slug',
    'en'
);

Enter fullscreen mode Exit fullscreen mode

What you don't need

List of things I considered and decided against:

  • An i18n library (gettext, Symfony Translation, etc.) — For a blog, interface strings fit on two hands: "Read more", "Home", "min read". Two ternary operators in the template is sufficient. An i18n library with .po or .yaml files would be pure over-engineering.
  • Automatic language detection — Detecting Accept-Language and redirecting automatically is a bad idea. It breaks link sharing, surprises users, and causes indexation problems. The URL is the source of truth.
  • Database for translations — If your content is PHP files, your translations are PHP files. Architectural consistency has value in itself.
  • A single file with switch($lang) — Covered above. Unreadable once articles go past 200 lines.
  • Automatic translation (DeepL API, etc.) — Technically possible. But a technically dense blog article translated automatically is obvious to any developer. And it doesn't convince a recruiter that you can work in English. If the goal is demonstrating bilingualism, you actually have to write in English.

Summary of changed files

For an already-running blog, the exhaustive list of changes:

  • .htaccess — 2 RewriteRule lines for EN URLs
  • router.php — 2 corresponding PHP routing blocks
  • blog/template.phpblog_header() uses $lang for html[lang], og:locale, hreflang, breadcrumbs, nav, toggle; blog_footer() receives $lang to filter related articles
  • blog/posts.json — migrated to nested fr/en structure (one-shot script)
  • blog/index.php — absolute fetch /blog/posts.json, BLOG_LANG detection from URL, language filter, adapted URLs
  • blog/sitemap.php — added xhtml namespace and xhtml:link tags
  • For each existing article: blog/posts/slug.en.php to create

No new configuration files, no new dependencies, no stack change. All modifications are localized in files you're already maintaining.

In practice

This blog has been running with this architecture since the restructuring. Existing FR URLs haven't moved — no redirects to manage, no impact on already-indexed articles' rankings. EN versions are indexable as soon as they're created.

The only real cost is writing time: translating a 1000-word article takes between 30 minutes and an hour depending on technical density. That's the cost that can't be compressed — not the architecture.

If you already have a PHP blog without a framework and you're hesitating to add bilingual support because you think it's complex: the code isn't the hard part.