Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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