I Want to convert an html table to Array using php
I trying to get output like this:
array(
'name' => "test1",
'value' => "test1-1",
),
array(
'name' => "test2",
'value' => "test2-2",
),
my output now:
Array
(
[0] => Array
(
[test1] => test1-1
[test2] => test2-2
Is this possible?
<?php
$htmlContent = "<table>
<tr>
<th>test1</th>
<td>test1-1</td>
</tr>
<tr>
<th>test2</th>
<td>test2-2</td>
</tr>
</table>
"
$DOM = new DOMDocument();
$DOM->loadHTML($htmlContent);
$Header = $DOM->getElementsByTagName('th');
$Detail = $DOM->getElementsByTagName('td');
//#Get header name of the table
foreach($Header as $NodeHeader)
{
$aDataTableHeaderHTML[] = trim($NodeHeader->textContent);
}
//print_r($aDataTableHeaderHTML); die();
//#Get row data/detail table without header name as key
$i = 0;
$j = 0;
foreach($Detail as $sNodeDetail)
{
$aDataTableDetailHTML[$j][] = trim($sNodeDetail->textContent);
$i = $i + 1;
$j = $i % count($aDataTableHeaderHTML) == 0 ? $j + 1 : $j;
}
//print_r($aDataTableDetailHTML); die();
//#Get row data/detail table with header name as key and outer array index as row number
for($i = 0; $i < count($aDataTableDetailHTML); $i++)
{
for($j = 0; $j < count($aDataTableHeaderHTML); $j++)
{
$aTempData[$i][$aDataTableHeaderHTML[$j]] = $aDataTableDetailHTML[$i][$j];
}
}
$aDataTableDetailHTML = $aTempData; unset($aTempData);
print_r($aDataTableDetailHTML); die();
?>
……………………………………………………………………………………………………………………………………………………………………………………
2
Answers
I’ll do this just because it was fun using
explode
andstr_replace
— doing it without a PHP DOM parser ..Basically create a starting Main empty array using
explode( '</tr>', $table );
, and loop through it, add the temp arrays to it after stripping unwanted content (IE<tr>
andtrimming
)Your output should be:
UPDATE
Here is the PHP DOM code that does the same thing:
Your code is working too hard to try to keep the columnar data with the respective row.
To make things easier, iterate the row (
<tr>
) elements, then access the elements within the given row.Code (Demo)