PHP code example of kntnt / html-to-markdown

1. Go to this page and download the library: Download kntnt/html-to-markdown library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kntnt / html-to-markdown example snippets


use Kntnt\HtmlToMarkdown\HtmlToMarkdown;

$markdown = HtmlToMarkdown::convert('<strong>Bold Text</strong>');
// => **Bold Text**

$markdown = HtmlToMarkdown::convert(
    '<img src="/assets/image.png" />',
    domain: 'https://example.com',
);
// => ![](https://example.com/assets/image.png)

use Kntnt\HtmlToMarkdown\Converter\Converter;
use Kntnt\HtmlToMarkdown\Converter\Options;
use Kntnt\HtmlToMarkdown\Plugin\Base\BasePlugin;
use Kntnt\HtmlToMarkdown\Plugin\Commonmark\CommonmarkPlugin;
use Kntnt\HtmlToMarkdown\Plugin\Strikethrough\StrikethroughPlugin;
use Kntnt\HtmlToMarkdown\Plugin\Table\TablePlugin;

$converter = new Converter(
    plugins: [
        new BasePlugin(),
        new CommonmarkPlugin(),
        new StrikethroughPlugin(),
        new TablePlugin(),
    ],
);

$markdown = $converter->convertString(
    '<h1>Title</h1><table><tr><th>A</th></tr><tr><td>1</td></tr></table>',
    new Options(domain: 'https://example.com'),
);

new CommonmarkPlugin(
    emDelimiter: '_',          // default "*"
    strongDelimiter: '__',     // default "**"
    horizontalRule: '---',     // default "* * *"
    bulletListMarker: '+',     // default "-"
    codeBlockFence: '~~~',     // default "

$converter->convertString($html, new Options(
    

use Dom\Node;
use Kntnt\HtmlToMarkdown\Converter\Buffer;
use Kntnt\HtmlToMarkdown\Converter\Context;
use Kntnt\HtmlToMarkdown\Converter\Converter;
use Kntnt\HtmlToMarkdown\Converter\Plugin;
use Kntnt\HtmlToMarkdown\Converter\Priority;
use Kntnt\HtmlToMarkdown\Converter\RenderStatus;
use Kntnt\HtmlToMarkdown\Dom\Dom;

final class HighlightPlugin implements Plugin
{
    public function name(): string
    {
        return 'highlight';
    }

    public function init(Converter $converter): void
    {
        $converter->register->renderer($this->render(...), Priority::STANDARD);
    }

    private function render(Context $ctx, Buffer $w, Node $node): RenderStatus
    {
        if (Dom::nodeName($node) !== 'mark') {
            return RenderStatus::TryNext;
        }

        $inner = new Buffer();
        $ctx->renderChildNodes($ctx, $inner, $node);
        $w->write('==' . $inner->bytes() . '==');

        return RenderStatus::Success;
    }
}

$converter = new Converter([
    new BasePlugin(),
    new CommonmarkPlugin(),
    new HighlightPlugin(),
]);