Skip to content

Instantly share code, notes, and snippets.

@csskevin
Last active September 6, 2019 23:43
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 csskevin/55254f7e7190b4839f1000a24ebab273 to your computer and use it in GitHub Desktop.
Save csskevin/55254f7e7190b4839f1000a24ebab273 to your computer and use it in GitHub Desktop.
Just a little prototype for converting html tables to associative arrays
<?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