Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML elements to an array

Tags:

sql

php

parsing

xml

I have some simple XML which I would like to parse into an array in PHP so that I can build some dynamic SQL inserts.

Sample XML:

<Data>
    <Key>1</Key>
    <Column>Value 1</Column>
    <Column2>Value 2</Column>
</Data>

Data will be passed to PHP via http POST.

What's the easiest way to do this? There should always be one instance of but would like the option to take multiple instances from one POST.

I can certainly build out some code to parse specific PHP, but I'd like to use a single piece of code to handle the data dynamically so that it can be used to create inserts for multiple tables.

like image 488
andyknas Avatar asked Aug 02 '26 04:08

andyknas


1 Answers

Well, assuming that you want a result of

array(
    1 => array(
        'Value 1',
        'Value 2',
    )
)

And assuming a structure of

<root>
    <Data>
        <!-- key and column entities -->
    </Data>
    <Data>
        <!-- key and column entities -->
    </Data>
    <Data>
        <!-- key and column entities -->
    </Data>
</root>

You could do something like (I prefer DomDocument):

$dom = new DomDocument();
$dom->loadXml($xmlString);
$dataElements = $dom->getElementsByTagName('Data');
$array = array();
foreach ($dataElements as $element) {
    $subarray = array();
    foreach ($element->childNodes as $node) {
        if (!$node instanceof DomElement) {
            continue;
        }
        $key = $node->tagName;
        $value = $node->textContent;
        $subarray[$key] = $value;
    }
    $array[] = $subarray;
}

With that edit, it'll turn:

<root>
    <Data>
        <Key>4</Key>
        <Foo>Bar</Foo>
    </Data>
    <Data>
        <Key>6</Key>
        <Bar>Baz</Bar>
    </Data>
</root>

Into:

array(
    array(
        'Key' => 4,
        'Foo' => 'Bar',
    ),
    array(
        'Key' => 6,
        'Bar' => 'Baz',
    ),
)
like image 160
ircmaxell Avatar answered Aug 03 '26 17:08

ircmaxell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!