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 The name of the parent node to search for (e.g. 'code')
104 private static function is_child_of($parent_name, $node)
106 for ($p = $node->parentNode; $p != false; $p = $p->parentNode) {
110 if ($p->nodeName == $parent_name)
120 * Recursive function to drill into the DOM and convert each node into Markdown from the inside out.
122 * Finds children of each node and convert those to #text nodes containing their Markdown equivalent,
123 * starting with the innermost element and working up to the outermost element.
127 private function convert_children($node)
129 // Don't convert HTML code inside <code> and <pre> blocks to Markdown - that should stay as HTML
130 if (self::is_child_of('pre', $node) || self::is_child_of('code', $node))
133 // If the node has children, convert those to Markdown first
134 if ($node->hasChildNodes()) {
135 $length = $node->childNodes->length;
137 for ($i = 0; $i < $length; $i++) {
138 $child = $node->childNodes->item($i);
139 $this->convert_children($child);
143 // Now that child nodes have been converted, convert the original node
144 $markdown = $this->convert_to_markdown($node);
146 // Create a DOM text node containing the Markdown equivalent of the original node
147 $markdown_node = $this->document->createTextNode($markdown);
149 // Replace the old $node e.g. "<h3>Title</h3>" with the new $markdown_node e.g. "### Title"
150 $node->parentNode->replaceChild($markdown_node, $node);
157 * Sends the body node to convert_children() to change inner nodes to Markdown #text nodes, then saves and
158 * returns the resulting converted document as a string in Markdown format.
160 * @return string|boolean The converted HTML as Markdown, or false if conversion failed
162 private function get_markdown()
164 // Work on the entire DOM tree (including head and body)
165 $input = $this->document->getElementsByTagName("html")->item(0);
170 // Convert all children of this root element. The DOMDocument stored in $this->doc will
171 // then consist of #text nodes, each containing a Markdown version of the original node
173 $this->convert_children($input);
175 // Sanitize and return the body contents as a string.
176 $markdown = $this->document->saveHTML(); // stores the DOMDocument as a string
177 $markdown = html_entity_decode($markdown, ENT_QUOTES, 'UTF-8');
178 $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
179 $markdown = preg_replace("/<!DOCTYPE [^>]+>/", "", $markdown); // Strip doctype declaration
180 $unwanted = array('<html>', '</html>', '<body>', '</body>', '<head>', '</head>', '<?xml encoding="UTF-8">', '
');
181 $markdown = str_replace($unwanted, '', $markdown); // Strip unwanted tags
182 $markdown = trim($markdown, "\n\r\0\x0B");
184 $this->output = $markdown;
191 * Convert to Markdown
193 * Converts an individual node into a #text node containing a string of its Markdown equivalent.
195 * Example: An <h3> node with text content of "Title" becomes a text node with content of "### Title"
198 * @return string The converted HTML as Markdown
200 private function convert_to_markdown($node)
202 $tag = $node->nodeName; // the type of element, e.g. h1
203 $value = $node->nodeValue; // the value of that element, e.g. The Title
205 // Strip nodes named in remove_nodes
206 $tags_to_remove = explode(' ', $this->options['remove_nodes']);
207 if ( in_array($tag, $tags_to_remove) )
212 $markdown = (trim($value)) ? rtrim($value) . PHP_EOL . PHP_EOL : '';
215 $markdown = PHP_EOL . $this->convert_code($node) . PHP_EOL;
219 $markdown = $this->convert_header($tag, $node);
222 $markdown = "### " . $value . PHP_EOL . PHP_EOL;
225 $markdown = "#### " . $value . PHP_EOL . PHP_EOL;
228 $markdown = "##### " . $value . PHP_EOL . PHP_EOL;
231 $markdown = "###### " . $value . PHP_EOL . PHP_EOL;
237 $markdown = $this->convert_emphasis($tag, $value);
240 $markdown = "- - - - - -" . PHP_EOL . PHP_EOL;
243 $markdown = " " . PHP_EOL;
246 $markdown = $this->convert_blockquote($node);
249 $markdown = $this->convert_code($node);
253 $markdown = $value . PHP_EOL;
256 $markdown = $this->convert_list($node);
259 $markdown = $this->convert_image($node);
262 $markdown = $this->convert_anchor($node);
265 $markdown = preg_replace('~\s+~', ' ', $value);
266 $markdown = preg_replace('~^#~', '\\\\#', $markdown);
272 $markdown = ($this->options['strip_tags']) ? $value . PHP_EOL . PHP_EOL : html_entity_decode($node->C14N());
275 // If strip_tags is false (the default), preserve tags that don't have Markdown equivalents,
276 // such as <span> nodes on their own. C14N() canonicalizes the node to a string.
277 // See: http://www.php.net/manual/en/domnode.c14n.php
278 $markdown = ($this->options['strip_tags']) ? $value : html_entity_decode($node->C14N());
288 * Converts h1 and h2 headers to Markdown-style headers in setext style,
289 * matching the number of underscores with the length of the title.
291 * e.g. Header 1 Header Two
292 * ======== ----------
294 * Returns atx headers instead if $this->options['header_style'] is "atx"
296 * e.g. # Header 1 ## Header Two
298 * @param string $level The header level, including the "h". e.g. h1
299 * @param string $node The node to convert.
300 * @return string The Markdown version of the header.
302 private function convert_header($level, $node)
304 $content = $node->nodeValue;
306 if (!$this->is_child_of('blockquote', $node) && $this->options['header_style'] == "setext") {
307 $length = (function_exists('mb_strlen')) ? mb_strlen($content, 'utf-8') : strlen($content);
308 $underline = ($level == "h1") ? "=" : "-";
309 $markdown = $content . PHP_EOL . str_repeat($underline, $length) . PHP_EOL . PHP_EOL; // setext style
311 $prefix = ($level == "h1") ? "# " : "## ";
312 $markdown = $prefix . $content . PHP_EOL . PHP_EOL; // atx style
320 * Converts inline styles
321 * This function is used to render strong and em tags
323 * eg <strong>bold text</strong> becomes **bold text** or __bold text__
326 * @param string $value
329 private function convert_emphasis($tag, $value)
331 if ($tag == 'i' || $tag == 'em') {
332 $markdown = $this->options['italic_style'] . $value . $this->options['italic_style'];
334 $markdown = $this->options['bold_style'] . $value . $this->options['bold_style'];
344 * Converts <img /> tags to Markdown.
346 * e.g. <img src="/path/img.jpg" alt="alt text" title="Title" />
347 * becomes ![alt text](/path/img.jpg "Title")
352 private function convert_image($node)
354 $src = $node->getAttribute('src');
355 $alt = $node->getAttribute('alt');
356 $title = $node->getAttribute('title');
359 $markdown = '![' . $alt . '](' . $src . ' "' . $title . '")'; // No newlines added. <img> should be in a block-level element.
361 $markdown = '![' . $alt . '](' . $src . ')';
371 * Converts <a> tags to Markdown.
373 * e.g. <a href="http://modernnerd.net" title="Title">Modern Nerd</a>
374 * becomes [Modern Nerd](http://modernnerd.net "Title")
379 private function convert_anchor($node)
381 $href = $node->getAttribute('href');
382 $title = $node->getAttribute('title');
383 $text = $node->nodeValue;
386 $markdown = '[' . $text . '](' . $href . ' "' . $title . '")';
388 $markdown = '[' . $text . '](' . $href . ')';
391 // Append a space if the node after this one is also an anchor
392 $next_node_name = $this->get_next_node_name($node);
394 if ($next_node_name == 'a')
395 $markdown = $markdown . ' ';
404 * Converts <ul> and <ol> lists to Markdown.
409 private function convert_list($node)
411 // If parent is an ol, use numbers, otherwise, use dashes
412 $list_type = $node->parentNode->nodeName;
413 $value = $node->nodeValue;
415 if ($list_type == "ul") {
416 $markdown = "- " . trim($value) . PHP_EOL;
418 $number = $this->get_position($node);
419 $markdown = $number . ". " . trim($value) . PHP_EOL;
429 * Convert code tags by indenting blocks of code and wrapping single lines in backticks.
431 * @param DOMNode $node
434 private function convert_code($node)
436 // Store the content of the code block in an array, one entry for each line
440 $code_content = html_entity_decode($this->document->saveHTML($node));
441 $code_content = str_replace(array("<code>", "</code>"), "", $code_content);
442 $code_content = str_replace(array("<pre>", "</pre>"), "", $code_content);
444 $lines = preg_split('/\r\n|\r|\n/', $code_content);
445 $total = count($lines);
447 // If there's more than one line of code, prepend each line with four spaces and no backticks.
448 if ($total > 1 || $node->nodeName === 'pre') {
450 // Remove the first and last line if they're empty
451 $first_line = trim($lines[0]);
452 $last_line = trim($lines[$total - 1]);
453 $first_line = trim($first_line, "
"); //trim XML style carriage returns too
454 $last_line = trim($last_line, "
");
456 if (empty($first_line))
459 if (empty($last_line))
463 foreach ($lines as $line) {
464 $line = str_replace('
', '', $line);
465 $markdown .= " " . $line;
466 // Add newlines, except final line of the code
467 if ($count != $total)
468 $markdown .= PHP_EOL;
471 $markdown .= PHP_EOL;
473 } else { // There's only one line of code. It's a code span, not a block. Just wrap it with backticks.
475 $markdown .= "`" . $lines[0] . "`";
486 * Prepend blockquotes with > chars.
491 private function convert_blockquote($node)
493 // Contents should have already been converted to Markdown by this point,
494 // so we just need to add ">" symbols to each line.
498 $quote_content = trim($node->nodeValue);
500 $lines = preg_split('/\r\n|\r|\n/', $quote_content);
502 $total_lines = count($lines);
504 foreach ($lines as $i => $line) {
505 $markdown .= "> " . $line . PHP_EOL;
506 if ($i + 1 == $total_lines)
507 $markdown .= PHP_EOL;
517 * Returns the numbered position of a node inside its parent
520 * @return int The numbered position of the node, starting at 1.
522 private function get_position($node)
524 // Get all of the nodes inside the parent
525 $list_nodes = $node->parentNode->childNodes;
526 $total_nodes = $list_nodes->length;
530 // Loop through all nodes and find the given $node
531 for ($a = 0; $a < $total_nodes; $a++) {
532 $current_node = $list_nodes->item($a);
534 if ($current_node->isSameNode($node))
545 * Return the name of the node immediately after the passed one.
548 * @return string|null The node name (e.g. 'h1') or null.
550 private function get_next_node_name($node)
552 $next_node_name = null;
554 $current_position = $this->get_position($node);
555 $next_node = $node->parentNode->childNodes->item($current_position);
558 $next_node_name = $next_node->nodeName;
560 return $next_node_name;
567 * Magic method to return Markdown output when HTML_To_Markdown instance is treated as a string.
571 public function __toString()
573 return $this->output();
580 * Getter for the converted Markdown contents stored in $this->output
584 public function output()
586 if (!$this->output) {
589 return $this->output;