Page 1 of 1

Wow, Check Out This XML2Array Function

Posted: Mon Nov 17, 2008 4:14 pm
by volomike
It doesn't get any easier than this.

Code: Select all

 
function XML2Array($s) {
    preg_match_all("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $s, $asMatches, PREG_SET_ORDER);
    $asItems = array();
    foreach ($asMatches as $sVal) {
        $oItem = (object) array();
        $oItem->Full = $sVal[0];
        $oItem->Before = $sVal[1];
        $oItem->Tag = $sVal[2];
        $oItem->Value = $sVal[3];
        $oItem->After = $sVal[4];
        array_push($asItems, (array) $oItem);
    }
    return $asItems;    
}
Now, it won't ignore comments and only goes one level deep, but it's pretty darn cool, none-the-less.

Re: Wow, Check Out This XML2Array Function

Posted: Wed Nov 19, 2008 2:50 pm
by requinix
Here's something for you to test your code on. It has two noticeable problems, besides what you've mentioned.

Code: Select all

<records>
    <record id="1">
        <title>First</title>
        <description>This is the first record.
It has nothing important in it.</description>
    </record>
    <record id="2">
        <title>Second</title>
        <description>This is the second record.
It doesn't have anything important either.</description>
    </record>
    <record id="3">
        <title>Third</title>
        <description>This is the third record.
It is also the last record, and also has nothing important.</description>
    </record>
</records>

Re: Wow, Check Out This XML2Array Function

Posted: Wed Nov 19, 2008 3:01 pm
by Christopher
Obviously it returns an object rather than an array, but how does your function perform compared to simplexml_load_string() ?

Re: Wow, Check Out This XML2Array Function

Posted: Wed Nov 19, 2008 6:01 pm
by volomike
Well, if you have the power to adjust your XML, and don't particularly have the power to get the XML API stuff loaded on a shared host, then the function might be useful to you.