simplexml to array

Sometimes dealing with PHP’s simplexml object can be annoying, and you just wish it was a simple array. There are a ton of functions out there for that, but I’ve found this one works best =)

Source: http://www.php.net/manual/en/ref.simplexml.php

function simplexml2array($xml) {
	if (get_class($xml) == 'SimpleXMLElement') {
		$attributes = $xml->attributes();
		foreach($attributes as $k=>$v) {
			if ($v) $a[$k] = (string) $v;
		}
		$x = $xml;
		$xml = get_object_vars($xml);
	}
	if (is_array($xml)) {
		if (count($xml) == 0) return (string) $x; // for CDATA
		foreach($xml as $key=>$value) {
			$r[$key] = $this->simplexml2array($value);
		}
		if (isset($a)) $r['@attributes'] = $a;    // Attributes
		return $r;
	}
	return (string) $xml;
}

7 Comments to simplexml to array

  1. fred wolf's Gravatar fred wolf
    May 28, 2010 at 12:46 pm | Permalink

    thank you James,

    I was looking for somtething like that. It’s perfect

  2. pedro's Gravatar pedro
    June 29, 2010 at 3:43 am | Permalink

    You COPY this code from Daniel FAIVRE 2005, SEE
    http://theserverpages.com/php/manual/en/ref.simplexml.php

  3. Bob's Gravatar Bob
    March 10, 2011 at 8:34 am | Permalink

    I think you mean “You’re correct”. “Your” means belonging to you as in “Your children”. You’re is short for you are as in “You are correct”.

    Now you’re correct!

  4. April 23, 2012 at 6:15 am | Permalink

    Thanks man for copying this function.
    It works perfectly. You have a great eye for copying things !

  5. October 10, 2012 at 10:34 am | Permalink

    LIttle fix:

    if (is_object($xml) && get_class($xml) == ‘SimpleXMLElement’) {

    Else it could produce warnings…

  6. December 11, 2012 at 2:45 pm | Permalink

    Awesome! Thanks for the snippet.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>