3 * Class HTML_To_Markdown
5 * A helper class to convert HTML to Markdown.
8 * @author Nick Cernis <nick@cern.is>
9 * @link https://github.com/nickcernis/html2markdown/ Latest version on GitHub.
10 * @link http://twitter.com/nickcernis Nick on twitter.
11 * @license http://www.opensource.org/licenses/mit-license.php MIT
13 class HTML_To_Markdown
16 * @var DOMDocument The root of the document tree that holds our HTML.
21 * @var string|boolean The Markdown version of the original HTML, or false if conversion failed
26 * @var array Class-wide options users can override.
28 private $options = array(
29 'header_style' => 'setext', // Set to "atx" to output H1 and H2 headers as # Header1 and ## Header2
30 'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML
31 'strip_tags' => false, // Set to true to strip tags that don't have markdown equivalents. N.B. Strips tags, not their content. Useful to clean MS Word HTML output.
32 'bold_style' => '**', // Set to '__' if you prefer the underlined style
33 'italic_style' => '*', // Set to '_' if you prefer the underlined style
34 'remove_nodes' => '', // space-separated list of dom nodes that should be removed. example: "meta style script"
41 * Set up a new DOMDocument from the supplied HTML, convert it to Markdown, and store it in $this->$output.
43 * @param string $html The HTML to convert to Markdown.
44 * @param array $overrides [optional] List of style and error display overrides.
46 public function __construct($html = null, $overrides = null)
49 $this->options = array_merge($this->options, $overrides);
52 $this->convert($html);
57 * Setter for conversion options
62 public function set_option($name, $value)
64 $this->options[$name] = $value;
71 * Loads HTML and passes to get_markdown()
74 * @return string The Markdown version of the html
76 public function convert($html)
78 $html = preg_replace('~>\s+<~', '><', $html); // Strip white space between tags to prevent creation of empty #text nodes
80 $this->document = new DOMDocument();
82 if ($this->options['suppress_errors'])
83 libxml_use_internal_errors(true); // Suppress conversion errors (from http://bit.ly/pCCRSX )
85 $this->document->loadHTML('<?xml encoding="UTF-8">' . $html); // Hack to load utf-8 HTML (from http://bit.ly/pVDyCt )
86 $this->document->encoding = 'UTF-8';
88 if ($this->options['suppress_errors'])
89 libxml_clear_errors();
91 return $this->get_markdown($html);
98 * Is the node a child of the given parent tag?
100 * @param $parent_name string|array The name of the parent node(s) to search for e.g. 'code' or array('pre', 'code')
104 private static function is_child_of($parent_name, $node)
106 for ($p = $node->parentNode; $p != false; $p = $p->parentNode) {
110 if ( is_array($parent_name) && in_array($p->nodeName, $parent_name) )
113 if ($p->nodeName == $parent_name)
123 * Recursive function to drill into the DOM and convert each node into Markdown from the inside out.
125 * Finds children of each node and convert those to #text nodes containing their Markdown equivalent,
126 * starting with the innermost element and working up to the outermost element.
130 private function convert_children($node)
132 // Don't convert HTML code inside <code> and <pre> blocks to Markdown - that should stay as HTML
133 if (self::is_child_of(array('pre', 'code'), $node))
136 // If the node has children, convert those to Markdown first
137 if ($node->hasChildNodes()) {
138 $length = $node->childNodes->length;
140 for ($i = 0; $i < $length; $i++) {
141 $child = $node->childNodes->item($i);
142 $this->convert_children($child);
146 // Now that child nodes have been converted, convert the original node
147 $markdown = $this->convert_to_markdown($node);
149 // Create a DOM text node containing the Markdown equivalent of the original node
150 $markdown_node = $this->document->createTextNode($markdown);
152 // Replace the old $node e.g. "<h3>Title</h3>" with the new $markdown_node e.g. "### Title"
153 $node->parentNode->replaceChild($markdown_node, $node);
160 * Sends the body node to convert_children() to change inner nodes to Markdown #text nodes, then saves and
161 * returns the resulting converted document as a string in Markdown format.
163 * @return string|boolean The converted HTML as Markdown, or false if conversion failed
165 private function get_markdown()
167 // Work on the entire DOM tree (including head and body)
168 $input = $this->document->getElementsByTagName("html")->item(0);
173 // Convert all children of this root element. The DOMDocument stored in $this->doc will
174 // then consist of #text nodes, each containing a Markdown version of the original node
176 $this->convert_children($input);
178 // Sanitize and return the body contents as a string.
179 $markdown = $this->document->saveHTML(); // stores the DOMDocument as a string
180 $markdown = html_entity_decode($markdown, ENT_QUOTES, 'UTF-8');
181 $markdown = html_entity_decode($markdown, ENT_QUOTES, 'UTF-8'); // Double decode to cover cases like &nbsp; http://www.php.net/manual/en/function.htmlentities.php#99984
182 $markdown = preg_replace("/<!DOCTYPE [^>]+>/", "", $markdown); // Strip doctype declaration
183 $unwanted = array('<html>', '</html>', '<body>', '</body>', '<head>', '</head>', '<?xml encoding="UTF-8">', '
');
184 $markdown = str_replace($unwanted, '', $markdown); // Strip unwanted tags
185 $markdown = trim($markdown, "\n\r\0\x0B");
187 $this->output = $markdown;
194 * Convert to Markdown
196 * Converts an individual node into a #text node containing a string of its Markdown equivalent.
198 * Example: An <h3> node with text content of "Title" becomes a text node with content of "### Title"
201 * @return string The converted HTML as Markdown
203 private function convert_to_markdown($node)
205 $tag = $node->nodeName; // the type of element, e.g. h1
206 $value = $node->nodeValue; // the value of that element, e.g. The Title
208 // Strip nodes named in remove_nodes
209 $tags_to_remove = explode(' ', $this->options['remove_nodes']);
210 if ( in_array($tag, $tags_to_remove) )
215 $markdown = (trim($value)) ? rtrim($value) . PHP_EOL . PHP_EOL : '';
218 $markdown = PHP_EOL . $this->convert_code($node) . PHP_EOL;
222 $markdown = $this->convert_header($tag, $node);
225 $markdown = "### " . $value . PHP_EOL . PHP_EOL;
228 $markdown = "#### " . $value . PHP_EOL . PHP_EOL;
231 $markdown = "##### " . $value . PHP_EOL . PHP_EOL;
234 $markdown = "###### " . $value . PHP_EOL . PHP_EOL;
240 $markdown = $this->convert_emphasis($tag, $value);
243 $markdown = "- - - - - -" . PHP_EOL . PHP_EOL;
246 $markdown = " " . PHP_EOL;
249 $markdown = $this->convert_blockquote($node);
252 $markdown = $this->convert_code($node);
256 $markdown = $value . PHP_EOL;
259 $markdown = $this->convert_list($node);
262 $markdown = $this->convert_image($node);
265 $markdown = $this->convert_anchor($node);
268 $markdown = preg_replace('~\s+~', ' ', $value);
269 $markdown = preg_replace('~^#~', '\\\\#', $markdown);
275 $markdown = ($this->options['strip_tags']) ? $value . PHP_EOL . PHP_EOL : html_entity_decode($node->C14N());
278 // If strip_tags is false (the default), preserve tags that don't have Markdown equivalents,
279 // such as <span> nodes on their own. C14N() canonicalizes the node to a string.
280 // See: http://www.php.net/manual/en/domnode.c14n.php
281 $markdown = ($this->options['strip_tags']) ? $value : html_entity_decode($node->C14N());
291 * Converts h1 and h2 headers to Markdown-style headers in setext style,
292 * matching the number of underscores with the length of the title.
294 * e.g. Header 1 Header Two
295 * ======== ----------
297 * Returns atx headers instead if $this->options['header_style'] is "atx"
299 * e.g. # Header 1 ## Header Two
301 * @param string $level The header level, including the "h". e.g. h1
302 * @param string $node The node to convert.
303 * @return string The Markdown version of the header.
305 private function convert_header($level, $node)
307 $content = $node->nodeValue;
309 if (!$this->is_child_of('blockquote', $node) && $this->options['header_style'] == "setext") {
310 $length = (function_exists('mb_strlen')) ? mb_strlen($content, 'utf-8') : strlen($content);
311 $underline = ($level == "h1") ? "=" : "-";
312 $markdown = $content . PHP_EOL . str_repeat($underline, $length) . PHP_EOL . PHP_EOL; // setext style
314 $prefix = ($level == "h1") ? "# " : "## ";
315 $markdown = $prefix . $content . PHP_EOL . PHP_EOL; // atx style
323 * Converts inline styles
324 * This function is used to render strong and em tags
326 * eg <strong>bold text</strong> becomes **bold text** or __bold text__
329 * @param string $value
332 private function convert_emphasis($tag, $value)
334 if ($tag == 'i' || $tag == 'em') {
335 $markdown = $this->options['italic_style'] . $value . $this->options['italic_style'];
337 $markdown = $this->options['bold_style'] . $value . $this->options['bold_style'];
347 * Converts <img /> tags to Markdown.
349 * e.g. <img src="/path/img.jpg" alt="alt text" title="Title" />
350 * becomes ![alt text](/path/img.jpg "Title")
355 private function convert_image($node)
357 $src = $node->getAttribute('src');
358 $alt = $node->getAttribute('alt');
359 $title = $node->getAttribute('title');
362 $markdown = '![' . $alt . '](' . $src . ' "' . $title . '")'; // No newlines added. <img> should be in a block-level element.
364 $markdown = '![' . $alt . '](' . $src . ')';
374 * Converts <a> tags to Markdown.
376 * e.g. <a href="http://modernnerd.net" title="Title">Modern Nerd</a>
377 * becomes [Modern Nerd](http://modernnerd.net "Title")
382 private function convert_anchor($node)
384 $href = $node->getAttribute('href');
385 $title = $node->getAttribute('title');
386 $text = $node->nodeValue;
389 $markdown = '[' . $text . '](' . $href . ' "' . $title . '")';
391 $markdown = '[' . $text . '](' . $href . ')';
395 $markdown = html_entity_decode($node->C14N());
397 // Append a space if the node after this one is also an anchor
398 $next_node_name = $this->get_next_node_name($node);
400 if ($next_node_name == 'a')
401 $markdown = $markdown . ' ';
410 * Converts <ul> and <ol> lists to Markdown.
415 private function convert_list($node)
417 // If parent is an ol, use numbers, otherwise, use dashes
418 $list_type = $node->parentNode->nodeName;
419 $value = $node->nodeValue;
421 if ($list_type == "ul") {
422 $markdown = "- " . trim($value) . PHP_EOL;
424 $number = $this->get_position($node);
425 $markdown = $number . ". " . trim($value) . PHP_EOL;
435 * Convert code tags by indenting blocks of code and wrapping single lines in backticks.
437 * @param DOMNode $node
440 private function convert_code($node)
442 // Store the content of the code block in an array, one entry for each line
446 $code_content = html_entity_decode($node->C14N());
447 $code_content = str_replace(array("<code>", "</code>"), "", $code_content);
448 $code_content = str_replace(array("<pre>", "</pre>"), "", $code_content);
450 $lines = preg_split('/\r\n|\r|\n/', $code_content);
451 $total = count($lines);
453 // If there's more than one line of code, prepend each line with four spaces and no backticks.
454 if ($total > 1 || $node->nodeName === 'pre') {
456 // Remove the first and last line if they're empty
457 $first_line = trim($lines[0]);
458 $last_line = trim($lines[$total - 1]);
459 $first_line = trim($first_line, "
"); //trim XML style carriage returns too
460 $last_line = trim($last_line, "
");
462 if (empty($first_line))
465 if (empty($last_line))
469 foreach ($lines as $line) {
470 $line = str_replace('
', '', $line);
471 $markdown .= " " . $line;
472 // Add newlines, except final line of the code
473 if ($count != $total)
474 $markdown .= PHP_EOL;
477 $markdown .= PHP_EOL;
479 } else { // There's only one line of code. It's a code span, not a block. Just wrap it with backticks.
481 $markdown .= "`" . $lines[0] . "`";
492 * Prepend blockquotes with > chars.
497 private function convert_blockquote($node)
499 // Contents should have already been converted to Markdown by this point,
500 // so we just need to add ">" symbols to each line.
504 $quote_content = trim($node->nodeValue);
506 $lines = preg_split('/\r\n|\r|\n/', $quote_content);
508 $total_lines = count($lines);
510 foreach ($lines as $i => $line) {
511 $markdown .= "> " . $line . PHP_EOL;
512 if ($i + 1 == $total_lines)
513 $markdown .= PHP_EOL;
523 * Returns the numbered position of a node inside its parent
526 * @return int The numbered position of the node, starting at 1.
528 private function get_position($node)
530 // Get all of the nodes inside the parent
531 $list_nodes = $node->parentNode->childNodes;
532 $total_nodes = $list_nodes->length;
536 // Loop through all nodes and find the given $node
537 for ($a = 0; $a < $total_nodes; $a++) {
538 $current_node = $list_nodes->item($a);
540 if ($current_node->isSameNode($node))
551 * Return the name of the node immediately after the passed one.
554 * @return string|null The node name (e.g. 'h1') or null.
556 private function get_next_node_name($node)
558 $next_node_name = null;
560 $current_position = $this->get_position($node);
561 $next_node = $node->parentNode->childNodes->item($current_position);
564 $next_node_name = $next_node->nodeName;
566 return $next_node_name;
573 * Magic method to return Markdown output when HTML_To_Markdown instance is treated as a string.
577 public function __toString()
579 return $this->output();
586 * Getter for the converted Markdown contents stored in $this->output
590 public function output()
592 if (!$this->output) {
595 return $this->output;