Repository navigation
Expand file tree
/
Copy pathmarkdown_converter.php
More file actions
75 lines (72 loc) · 2.49 KB
/
Copy pathmarkdown_converter.php
File metadata and controls
75 lines (72 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* \file
* \brief Simple Mardown to HTML utility file.
*
* PHP version 8.1
*
* @category Documentation
* @package Lwt_Documentation
* @author HugoFara <hugo.farajallah@protonmail.com>
* @license Unlicense <http://unlicense.org/>
* @link https://hugofara.github.io/lwt/docs/php/files/src-php-markdown-converter.html
* @since 2.0.3-fork
*/
require __DIR__ . '/../../vendor/autoload.php';
use League\CommonMark\GithubFlavoredMarkdownConverter;
/**
* Convert a markdown file to HTML and return the result.
*
* @param string $file_path Full path for the file to use, including extension.
*
* @return string An HTML-formatted string
*/
function markdown_converter($file_path)
{
$converter = new GithubFlavoredMarkdownConverter();
$markdown = file_get_contents($file_path);
return $converter->convert($markdown)->getContent();
}
/**
* Prepapre the integration of a Markdown file into info.html.
*
* Headers are incremented by one level. File name become an ID.
*
* @param string $file_path Full path for the file to use, including extension (should be ".md")
*/
function markdown_integration($file_path): void
{
$id = basename($file_path, ".md");
$html = markdown_converter($file_path);
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
$dom = new DOMDocument();
$dom->loadHTML($html);
for ($i = 7; $i > 0; $i--) {
$headers = $dom->getElementsByTagName('h' . $i);
for ($j = $headers->length; --$j >= 0;) {
$old_header = $headers->item($j);
if ($i == 1) {
//'<h2 name="' . $id . '" id="' . $id . '">
// ▶ $old_header->nodeValue - <a href="#">[↑]</a></h2>';
$link = $dom->createElement('a', '[↑]');
$link->setAttribute('href', '#');
$new_header = $dom->createElement(
'h2', '▶ ' . $old_header->nodeValue . ' - '
);
$new_header->setAttribute('id', $id);
$new_header->setAttribute('name', $id);
$new_header->appendChild($link);
} else {
$new_header = $dom->createElement(
'h' . ($i + 1), $old_header->nodeValue
);
}
$old_header->parentNode->replaceChild($new_header, $old_header);
}
}
$output = $dom->saveHTML($dom->lastChild->firstChild);
// Delete the <body></body> tags
$output = substr(substr($output, 6), 0, -7);
echo $output;
}
?>