Skip to content

Instantly share code, notes, and snippets.

@franz-josef-kaiser
Last active December 13, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franz-josef-kaiser/4944232 to your computer and use it in GitHub Desktop.
Save franz-josef-kaiser/4944232 to your computer and use it in GitHub Desktop.
Example for DOMDocument parser used to create a HTML table.
<?php
$dom = new DOMDocument( '' );
$root = $dom->createElement( 'html' );
$root = $dom->appendChild( $root );
$body = $dom->createElement( 'body' );
$body = $root->appendChild( $body );
$table = $dom->createElement( 'table' );
$table = $body->appendChild( $table );
$thead = $dom->createElement( 'thead' );
$thead = $table->appendChild( $thead );
$thead_tr = $dom->createElement( 'tr' );
$thead_tr = $thead->appendChild( $thead_tr );
$tbody = $dom->createElement( 'tbody' );
$tbody = $table->appendChild( $tbody );
$content = array(
'Feed On Offer' => range( 'a', 'z' ),
'Digestibility (%)' => range( 1, 26 ),
'Equivalent to' => range( 'a', 'z' ),
);
foreach ( $content as $th => $val )
{
$td = $dom->createElement( 'td' );
$td = $thead_tr->appendChild( $td );
$th = $dom->createTextNode( $th );
$th = $td->appendChild( $th );
$tbody_tr = $dom->createElement( 'tr' );
$tbody_tr = $tbody->appendChild( $tbody_tr );
foreach ( $val as $v )
{
$td = $dom->createElement( 'td' );
$td = $tbody_tr->appendChild( $td );
$v = $dom->createTextNode( $v );
$v = $td->appendChild( $v );
}
}
$dom->saveHTML();
// @TODO Test if we need to remove `html\body` tags
$html = '';
$nodes = $dom->getElementsByTagName( 'body' )->item(0)->childNodes;
foreach ( $nodes as $el )
$html .= $dom->saveXML( $el, LIBXML_NOEMPTYTAG );
echo $html;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment