Last active
September 6, 2019 23:43
-
-
Save csskevin/55254f7e7190b4839f1000a24ebab273 to your computer and use it in GitHub Desktop.
Just a little prototype for converting html tables to associative arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Table2Array | |
{ | |
public static function convert2HorizontalTable($html) | |
{ | |
$dom = new DOMDocument; | |
@$dom->loadHTML($html); | |
$xpath = new DOMXPath($dom); | |
$tables = array(); | |
foreach ($xpath->query('//table') as $table) { | |
$header = array(); | |
$headcells = $xpath->query('*/tr|tr', $table); | |
foreach($headcells as $th) | |
{ | |
array_push($header, trim($th->textContent)); | |
} | |
$object = array(); | |
foreach($xpath->query("*/tr|tr", $table) as $tr) | |
{ | |
$currentName = ''; | |
$cells = $xpath->query('td|th', $tr); | |
if(count($cells) === count($headcells)) | |
{ | |
$i = 0; | |
foreach($cells as $td) | |
{ | |
$content = trim($td->textContent); | |
if($i === 0) | |
{ | |
$currentName = $content; | |
$object[$currentName] = array(); | |
} else { | |
if(array_key_exists($i, $header)) | |
{ | |
$object[$currentName][$header[$i]] = $content; | |
} | |
} | |
$i++; | |
} | |
} | |
} | |
$object = array_filter($object, function($item) { | |
return !empty($item); | |
}); | |
if(!empty($object)) { | |
array_push($tables, $object); | |
} | |
} | |
return $tables; | |
} | |
public static function mergeTables($tables) | |
{ | |
$values = array(); | |
foreach($tables as $table) | |
{ | |
foreach($table as $key => $items) | |
{ | |
$values[$key] = $items; | |
} | |
} | |
return $values; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment