<?php
$html = '<html>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Chad</td>
<td>10/23/1996</td>
</tr>
<tr>
<td>Rebecca</td>
<td>05/03/2001</td>
</tbody>
</table>
</body>
</html>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$headers = $dom->getElementsByTagName('th');
foreach($headers as $header) {
$keys[] = strtolower($header->nodeValue);
}
$rows = $dom->getElementsByTagName('tbody')->item(0)->getElementsByTagName('tr');
$result = [];
foreach($rows as $row) {
$item = [];
$cells = $row->getElementsByTagName('td');
foreach($keys as $i => $key) {
$item[$key] = $cells->item($i)->nodeValue;
}
$result[] = $item;
}
var_dump($result);
- Output for 5.6.38, 7.1.0 - 7.1.23, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- array(2) {
[0]=>
array(2) {
["name"]=>
string(4) "Chad"
["date"]=>
string(10) "10/23/1996"
}
[1]=>
array(2) {
["name"]=>
string(7) "Rebecca"
["date"]=>
string(10) "05/03/2001"
}
}
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
array(2) {
[0]=>
array(2) {
["name"]=>
string(4) "Chad"
["date"]=>
string(10) "10/23/1996"
}
[1]=>
array(2) {
["name"]=>
string(7) "Rebecca"
["date"]=>
string(10) "05/03/2001"
}
}
preferences:
164.5 ms | 402 KiB | 173 Q