Skip to content

HTML to Markdown Converter — PHP source

Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/*
 * html-to-markdown — supported HTML subset → Markdown converter.
 *
 * Language: PHP (8.x, standard library only).
 * CosmoDev polyglot showcase port of the `html-to-markdown` tool.
 * Ported from src/lib/html-to-markdown.ts (the canonical TypeScript lib);
 * the Go CLI twin lives at cli/html-to-markdown/html-to-markdown.go.
 *
 * A hand-rolled single-scan tag parser (no DOM) builds a node forest, then a
 * renderer emits Markdown blocks: h1-h6, p/div/blockquote, pre fences with
 * the language taken from class="language-*", ul/ol with 2-space (ul) and
 * 4-space (ol) nested indent, hr, br as two-spaces-newline; inline marks
 * strong/b/em/i/del/s/code render empty emphasis as nothing, links keep
 * verbatim titles, images decode alt/src. Unknown tags are transparent,
 * stray closers are ignored, unclosed tags auto-close at EOF, and text nodes
 * backslash-escape \ ` * _ [ ]. A '<' with no closing '>' is the one error.
 *
 * Entities decode via html_entity_decode(..., ENT_QUOTES | ENT_HTML5) — the
 * stdlib WHATWG table (the PHP counterpart of the TS lib's decodeHtml and
 * Go's html.UnescapeString): full named coverage plus numeric decimal/hex,
 * single pass, no double-decode ("x &amp;lt; y" stays "x &lt; y").
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

const H2M_VOID = ['br' => true, 'hr' => true, 'img' => true, 'meta' => true,
                  'link' => true, 'input' => true, 'source' => true];
const H2M_BLOCK = ['p' => true, 'div' => true, 'blockquote' => true, 'pre' => true,
                   'ul' => true, 'ol' => true, 'hr' => true, 'h1' => true, 'h2' => true,
                   'h3' => true, 'h4' => true, 'h5' => true, 'h6' => true];

/** One forest node: text ($tag null) or element. */
final class H2MNode {
    public $tag;
    public $attrs = [];
    public $children = [];
    public $text = '';
    public function __construct(?string $tag = null, string $text = '') {
        $this->tag = $tag;
        $this->text = $text;
    }
}

/** One pass via the stdlib WHATWG table; malformed refs pass through. */
function h2m_decode_entities(string $s): string {
    return html_entity_decode($s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

function h2m_escape_markdown(string $s): string {
    return preg_replace('/[\\\\`*_\[\]]/', '\\\\$0', $s);
}

/** Parse into a node forest. Attribute values may be double-quoted,
 * single-quoted or bare; a quoted value may contain '>'. Returns
 * [$nodes, null] or [null, 'Unclosed tag']. */
function h2m_parse_html(string $raw): array {
    $roots = [];
    $stack = [];
    $i = 0;
    $len = strlen($raw);
    while ($i < $len) {
        $lt = strpos($raw, '<', $i);
        if ($lt === false) {
            h2m_append($roots, $stack, new H2MNode(null, substr($raw, $i)));
            break;
        }
        if ($lt > $i) {
            h2m_append($roots, $stack, new H2MNode(null, substr($raw, $i, $lt - $i)));
        }
        // Find the tag's '>', skipping quoted attribute values.
        $j = $lt + 1;
        $quote = null;
        while ($j < $len && ($raw[$j] !== '>' || $quote !== null)) {
            if ($quote === null && ($raw[$j] === '"' || $raw[$j] === "'")) {
                $quote = $raw[$j];
            } elseif ($quote !== null && $raw[$j] === $quote) {
                $quote = null;
            }
            $j++;
        }
        if ($j >= $len) {
            return [null, 'Unclosed tag'];
        }
        $inner = trim(substr($raw, $lt + 1, $j - $lt - 1));
        $i = $j + 1;

        if (str_starts_with($inner, '!--')) continue; // comment
        if (str_starts_with($inner, '!')) continue;   // doctype
        $closing = str_starts_with($inner, '/');
        $body = $closing ? substr($inner, 1) : preg_replace('/\/$/', '', $inner);
        if (!preg_match('/^([a-zA-Z][a-zA-Z0-9-]*)/', $body, $nm)) {
            continue; // not a real tag — browsers would show it as text; we drop it
        }
        $tag = strtolower($nm[1]);

        if ($closing) {
            for ($k = count($stack) - 1; $k >= 0; $k--) {
                if ($stack[$k]->tag === $tag) {
                    array_splice($stack, $k);
                    break;
                }
            }
            continue;
        }

        $elem = new H2MNode($tag);
        preg_match_all('/([a-zA-Z-]+)(?:\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+))?/', $body, $ams, PREG_SET_ORDER);
        foreach ($ams as $am) {
            // Values stay RAW here; href/src/alt are entity-decoded at use,
            // titles stay verbatim. The strip mirrors TS am[2].slice(1, -1):
            // quoted values lose their quotes, bare values lose their first
            // and last characters (same quirk the Go twin keeps for lock-step).
            $elem->attrs[strtolower($am[1])] = isset($am[2]) ? substr($am[2], 1, -1) : '';
        }
        h2m_append($roots, $stack, $elem);
        if (!isset(H2M_VOID[$tag]) && !str_ends_with($body, '/')) {
            $stack[] = $elem;
        }
    }
    return [$roots, null];
}

/** Append a node to the current open element's children, else the roots. */
function h2m_append(array &$roots, array &$stack, H2MNode $node): void {
    if ($stack) {
        $stack[count($stack) - 1]->children[] = $node;
    } else {
        $roots[] = $node;
    }
}

/** Inline content of one block: marks, links, images, escaped text. */
function h2m_render_inline(array $nodes): string {
    $out = '';
    foreach ($nodes as $n) {
        if ($n->tag === null) {
            // NBSP (U+00A0) is JS \s but not PCRE ASCII \s — normalize first.
            $t = str_replace("\xc2\xa0", ' ', h2m_decode_entities($n->text));
            $out .= preg_replace('/\s+/', ' ', h2m_escape_markdown($t));
        } elseif ($n->tag === 'br') {
            $out .= "  \n";
        } elseif ($n->tag === 'strong' || $n->tag === 'b') {
            $inner = trim(h2m_render_inline($n->children));
            if ($inner !== '') $out .= "**{$inner}**"; // empty emphasis renders as nothing
        } elseif ($n->tag === 'em' || $n->tag === 'i') {
            $inner = trim(h2m_render_inline($n->children));
            if ($inner !== '') $out .= "*{$inner}*";
        } elseif ($n->tag === 'del' || $n->tag === 's') {
            $inner = trim(h2m_render_inline($n->children));
            if ($inner !== '') $out .= "~~{$inner}~~";
        } elseif ($n->tag === 'code') {
            $inner = trim(h2m_render_inline($n->children));
            if ($inner !== '') $out .= "`{$inner}`";
        } elseif ($n->tag === 'a') {
            $href = h2m_decode_entities($n->attrs['href'] ?? '');
            $title = isset($n->attrs['title']) && $n->attrs['title'] !== '' ? " \"{$n->attrs['title']}\"" : '';
            $label = trim(h2m_render_inline($n->children));
            if ($label === '') $label = $href;
            $out .= "[{$label}]({$href}{$title})";
        } elseif ($n->tag === 'img') {
            $alt = trim(h2m_escape_markdown(h2m_decode_entities($n->attrs['alt'] ?? '')));
            $out .= "![{$alt}](" . h2m_decode_entities($n->attrs['src'] ?? '') . ')';
        } else {
            $out .= h2m_render_inline($n->children); // span and unknown tags are transparent
        }
    }
    return $out;
}

/** Concatenate the entity-decoded text under nodes (pre content only). */
function h2m_text_of(array $nodes): string {
    $out = '';
    foreach ($nodes as $c) {
        $out .= $c->tag === null ? h2m_decode_entities($c->text) : h2m_text_of($c->children);
    }
    return $out;
}

/** Render a sequence of nodes as Markdown blocks. */
function h2m_render_blocks(array $nodes): array {
    $out = [];
    $para = [];
    $flush = function () use (&$out, &$para) {
        if ($para) {
            $text = trim(h2m_render_inline($para));
            if ($text !== '') $out[] = $text;
            $para = [];
        }
    };
    foreach ($nodes as $n) {
        if (!isset(H2M_BLOCK[$n->tag])) {
            $para[] = $n;
            continue;
        }
        $flush();
        if ($n->tag === 'hr') {
            $out[] = '---';
        } elseif ($n->tag === 'p') {
            $text = trim(h2m_render_inline($n->children));
            if ($text !== '') $out[] = $text;
        } elseif ($n->tag === 'div') {
            array_push($out, ...h2m_render_blocks($n->children));
        } elseif ($n->tag === 'blockquote') {
            $inner = implode("\n\n", h2m_render_blocks($n->children));
            $lines = [];
            foreach (explode("\n", $inner) as $l) {
                $lines[] = $l !== '' ? "> {$l}" : '>';
            }
            $out[] = implode("\n", $lines);
        } elseif ($n->tag === 'pre') {
            $codeElem = null;
            foreach ($n->children as $c) {
                if ($c->tag === 'code') { $codeElem = $c; break; }
            }
            $lang = '';
            if ($codeElem !== null && preg_match('/language-([\w-]+)/', $codeElem->attrs['class'] ?? '', $lm)) {
                $lang = $lm[1];
            }
            $body = preg_replace('/\n+$/', '', h2m_text_of(($codeElem ?? $n)->children));
            $out[] = "```{$lang}\n{$body}\n```";
        } elseif ($n->tag === 'ul' || $n->tag === 'ol') {
            $out[] = h2m_render_list($n, 0);
        } else { // h1-h6
            $level = isset($n->tag[1]) && $n->tag[1] >= '1' && $n->tag[1] <= '6' ? (int)$n->tag[1] : 0;
            $out[] = str_repeat('#', $level) . ' ' . trim(h2m_render_inline($n->children));
        }
    }
    $flush();
    return $out;
}

/** ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
 * numbering restarted per list. */
function h2m_render_list(H2MNode $list, int $depth): string {
    $items = array_values(array_filter($list->children, fn($c) => $c->tag === 'li'));
    $ordered = $list->tag === 'ol';
    $lines = [];
    foreach (array_values($items) as $idx => $li) {
        $marker = $ordered ? ($idx + 1) . '.' : '-';
        $indent = str_repeat(' ', $depth === 0 ? 0 : ($ordered ? 4 : 2));
        // Split li children into inline content + nested lists.
        $inline = [];
        $nested = [];
        foreach ($li->children as $c) {
            if ($c->tag === 'ul' || $c->tag === 'ol') {
                $nested[] = h2m_render_list($c, $depth + 1);
            } else {
                $inline[] = $c;
            }
        }
        $text = trim(h2m_render_inline($inline));
        $lines[] = $text !== '' ? "{$indent}{$marker} {$text}" : "{$indent}{$marker}";
        array_push($lines, ...$nested);
    }
    return implode("\n", $lines);
}

/** Convert the supported HTML subset to Markdown. Never throws — the result
 * array carries output/error, mirroring HtmlToMarkdownResult. Empty or
 * whitespace-only input is NOT an error — the tool shows nothing. */
function html_to_markdown(string $raw): array {
    if (trim($raw) === '') {
        return ['output' => '', 'error' => null];
    }
    [$nodes, $err] = h2m_parse_html($raw);
    if ($err !== null) {
        return ['output' => '', 'error' => $err];
    }
    return ['output' => implode("\n\n", h2m_render_blocks($nodes)), 'error' => null];
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →