S
S
Sp1keazyYT2019-05-02 19:40:43
PHP
Sp1keazyYT, 2019-05-02 19:40:43

How to convert HTML tag tree to PHP array?

Good evening. There is some HTML file, taken by the file_get_contents function and printed by print_r ($file);
As a result, we get content with the following HTML structure:
cd9054a333.png
Task: convert the given structure into a PHP array and separate each tag into elements in the array.
What I did:
I tried to convert the structure to an array using the following code:

$buffer = file_get_contents("ссылка");

function XML2Array(SimpleXMLElement $parent)
{
    $array = array();

    foreach ($parent as $name => $element) {
        ($node = & $array[$name])
            && (1 === count($node) ? $node = array($node) : 1)
            && $node = & $node[];

        $node = $element->count() ? XML2Array($element) : trim($element);
    }

    return $array;
}

$xml   = simplexml_load_string($buffer);
$array = XML2Array($xml);
$array = array($xml->getName() => $array);

var_dump($array);

Here's what happened:
10ca46c526.png
Immediately there was a problem. I needed to transform each in the array as [0], [1], [2] and so on (array elements), but it turned out that the rest of all elements appeared in one element (under the numbers: [0], [1], [ 2] and so on).
How to do what I wrote above? Help me please!
The array should look something like this:
16e0e457b0.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question