Wow, Check Out This XML2Array Function

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
volomike
Forum Regular
Posts: 633
Joined: Wed Jan 16, 2008 9:04 am
Location: Myrtle Beach, South Carolina, USA

Wow, Check Out This XML2Array Function

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Wow, Check Out This XML2Array Function

Post 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>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Wow, Check Out This XML2Array Function

Post by Christopher »

Obviously it returns an object rather than an array, but how does your function perform compared to simplexml_load_string() ?
(#10850)
User avatar
volomike
Forum Regular
Posts: 633
Joined: Wed Jan 16, 2008 9:04 am
Location: Myrtle Beach, South Carolina, USA

Re: Wow, Check Out This XML2Array Function

Post 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.
Post Reply