简体   繁体   中英

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?

You have to use DOMElement in 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.

<?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

        <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
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM