/ Published in: PHP
Use PHP's DOM parser to convert a table into plain text (including links with images)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function html_table_to_plain($html, $id = NULL) { $plain_message = ''; $DOM = new DOMDocument(); $doc = $DOM->loadHTML($html); if ($doc === FALSE) { $plain_message = 'Failed to create DOM from HTML!'; throw new DOMException('Could not Load HTML into DOMDocument'); return $plain_message; } $titles_list = $DOM->getElementsByTagName('title'); if ($titles_list->length) $plain_message = '# '. $titles_list->item(0)->nodeValue ."\n\n"; $tables_list = $DOM->getElementsByTagName('table'); foreach ($tables_list as $table) { $plain_message .= "+==========\n"; $rows = $table->getElementsByTagName('tr'); $r = 0; $plain_message .= '| '; foreach ($headers as $th) { $plain_message .= '__'. $th->nodeValue .'__ | '; } } foreach ($cells as $cell) { foreach ($links as $l) { $plain_message .= '['; foreach ($imgs as $img) { $plain_message .='!['. $img->getAttribute('alt') .']('. $img->getAttribute('src') .')'; } } else { $plain_message .= $l->nodeValue; } $plain_message .= ']('. $l->getAttribute('href') .')'; } } else $plain_message .= $cell->nodeValue; $plain_message .= ' | '; } } } } $plain_message .= "\n+==========\n"; } } return $plain_message ; }