andyknas
andyknas

Reputation: 1957

Convert XML elements to an array

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.

Upvotes: 3

Views: 2901

Answers (2)

ircmaxell
ircmaxell

Reputation: 165271

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

Upvotes: 4

tamasd
tamasd

Reputation: 5913

SimpleXML is the name of the library what you are searching for: http://php.net/manual/en/book.simplexml.php

Upvotes: 1

Related Questions