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

Antti29
  • 2,953
  • 12
  • 34
  • 36
user2686713
  • 11
  • 1
  • 6
  • 2
    Possible duplicate of [How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – Calimero Oct 06 '17 at 07:23

2 Answers2

0

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
        )

)
AZinkey
  • 5,209
  • 5
  • 28
  • 46
0

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);
?>
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40