I am attempting to replace a table with divs so that it can display alright on a mobile device, here is the code so far.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->strictErrorChecking = false;
$dom->loadHTML($this->html);
$divID = 0;
foreach ($dom->getElementsByTagName('table') as $table) {
// for each table grab all rows
$rows = array();
$tableDiv = $dom->createElement('div');
$tableDiv->setAttribute('style', 'width: 95%; clear: both; margin: auto;');
$tableDiv->setAttribute('id', 'mobileTableGen_' . $divID . '_' . $page->name);
$divID++;
foreach ($table->getElementsByTagName('tr') as $row) {
$rows[] = $row;
}
foreach ($rows as $row) {
$cols = array();
foreach ($row->childNodes as $col) {
if ($col->nodeType != 3)
$cols[] = $col;
}
$numCols = count($cols);
$width = 100 / $numCols;
$rowDiv = $dom->createElement('div');
$rowDiv->setAttribute('style', 'clear: both; width: 100%;');
$rowDiv->setAttribute('id', 'mobileTableGen_' . $divID . '_' . $page->name);
$divID++;
foreach ($cols as $col) {
$div = $dom->createElement('div');
$div->setAttribute('style', 'width: ' . $width . '%; float: left;');
$div->setAttribute('id', 'mobileTableGen_' . $divID . '_' . $page->name);
$divID++;
foreach ($col->childNodes as $child) {
$div->appendChild($child);
}
$rowDiv->appendChild($div);
}
$tableDiv->appendChild($rowDiv);
}
$table->parentNode->replaceChild($tableDiv, $table);
}
$this->html = $dom->saveHTML();
The issue is at this line: $div->appendChild($child);
The child is always blank, but I can get the nodeValue just fine. So I can get the text of each cell from the table, but I am unable to get any html elements that are children of the nodes.
I tried replacing all the foreach with the equivalent for loop, having read that foreach loops on DOMNode objects can cause issues, but that produced the same result.