<table>
<tr>
<th>Alert ID</th>
<td>1002522</td>
</tr>
<tr>
<th>Client</th>
<th>Tri-County Eye</th>
</tr>
</table>
How to convert a HTML table into PHP array?
<table>
<tr>
<th>Alert ID</th>
<td>1002522</td>
</tr>
<tr>
<th>Client</th>
<th>Tri-County Eye</th>
</tr>
</table>
How to convert a HTML table into PHP array?
Arrange your table data like this
HTML
<table>
<tr>
<th>Alert ID</th> <!-- for array key -->
<td>1002522</td> <!-- for array value -->
</tr>
<tr>
<th>Client</th>
<td>Tri-County Eye</td>
</tr>
</table>
PHP
$html = "<table><tr><th>Alert ID</th><td>1002522</td></tr><tr><th>Client</th><td>Tri-County Eye</td></tr></table>";
$DOM = new DOMDocument;
$DOM->loadHTML($html);
$items = $DOM->getElementsByTagName('tr');
$array = [];
foreach ($items as $key => $item) {
foreach ($item->childNodes as $child) {
if ($child->tagName === 'th') {
$array[$key][$child->nodeValue] = $child->nextSibling->nodeValue;
}
}
}
echo "<pre>";
print_r($array);
OUTPUT
Array
(
[0] => Array
(
[Alert ID] => 1002522
)
[1] => Array
(
[Client] => Tri-County Eye
)
)
DOMElement::getElementsByTagName :- This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag name, in the order in which they are encountered in a preorder traversal of this element tree.
<?php
$html = "<table><tr><td>Name</td><td>Aman</td></tr></table>";
$DOM = new DOMDocument;
$DOM->loadHTML($html);
$items = $DOM->getElementsByTagName('tr')->item(0);
echo "<pre>";
print_r($items);
?>