LoginSignup
7
5

More than 3 years have passed since last update.

PHP Markdownを使ってMarkdownをHTMLに変換するバッチを作ってみた

Last updated at Posted at 2019-04-09

環境はWindows10。

PHP Markdown
GitHub:https://github.com/michelf/php-markdown
Packagist:https://packagist.org/packages/michelf/php-markdown

インストール

C:\xampp\htdocs\markdown>composer require michelf/php-markdown
Using version ^1.8 for michelf/php-markdown
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing michelf/php-markdown (1.8.0): Downloading (100%)
Writing lock file
Generating autoload files

テスト実行

適当なMarkdownをHTMLに変換してみます。

index.php
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Michelf\Markdown;

$markdown = <<< EOF
# 見出し h1
## 見出し h2
### 見出し h3
#### 見出し h4
##### 見出し h5
###### 見出し h6

- リスト
- リスト
    - リスト

1. 番号付きリスト
2. 番号付きリスト
    1. 番号付きリスト

**text**

*text*

~~text~~

`code`

> text
>> text

[title](http://...)

---

EOF;

$html = Markdown::defaultTransform($markdown);
?>

<html>
<head>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css" rel="stylesheet">
</head>
<body>
    <div class="markdown-body">
        <?= $html ?>
    </div>
</body>
</html>

image.png

CSSはGitHubのMarkdown CSSをCDN使って読み込んでいます。
効かない構文もあるけど、ちゃんと変換することができました。

変換バッチファイルを作成する

Markdownファイルを渡すとHTMLファイルに変換してくれるバッチファイルを作ってみます。

md2html.bat
@echo off
cd /d %~dp0

set PhpCommand="C:\xampp\php\php-win.exe -f"
set MarkdownFile=%1
set HtmlFile=%2
if "%HtmlFile%" equ "" (
    set HtmlFile=%MarkdownFile%.html
)

%PhpPath% md2html.php %MarkdownFile% %HtmlFile%

set ReturnCd=%ERRORLEVEL%
exit /b %ReturnCd%
md2html.php
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Michelf\Markdown;

$markdownFile   = $argv[1];
$htmlFile       = $argv[2];

$markdown = file_get_contents($markdownFile);

$html = Markdown::defaultTransform($markdown);

$html = <<< EOF
<html>
<head>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css" rel="stylesheet">
</head>
<body>
    <div class="markdown-body">
        ${html}
    </div>
</body>
</html>
EOF;

file_put_contents($htmlFile, $html);

>md2html.bat test.md test.html

こんな感じでMarkdownファイルを読み込ませるとHTMLファイルを作ってくれます。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5