[英]HTML table to array convert in PHP
<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?如何将 HTML 表格转换为 PHP 数组?
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. DOMElement::getElementsByTagName :-此函数返回具有给定标记名称的所有后代元素的类 DOMNodeList 的新实例,按照它们在此元素树的先序遍历中遇到的顺序。
<?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);
?>
Arrange your table data like this像这样排列你的表格数据
HTML 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 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
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.