Convert stdClass object with XML data to array in PHP

Given this object:

stdClass Object (
    [customerdata] => <TPSession userid="22" CustomerId="123456"LoginId="123456"/><TPSession userid="26" CustomerId="1234567"LoginId="1234567" />
)

How can I convert this XML data to an array using PHP?

+3
source share
3 answers

Just add it to the array:

$arr = (array) $obj;
+10
source

The Xml data in the question is invalid.

  • It does not have a root element.
  • CustomerId = "1234567" LoginId = "1234567" breaks XML parsing

You need to wrap it in the root element, solve the problem with the attribute, than use a simple XML parser to create an object that can be converted into an array.

Example

$o = new stdClass ();
$o->customerdata = '<TPSession userid="22" CustomerId="123456"LoginId="123456" /><TPSession userid="26" CustomerId="1234567"LoginId="1234567" />';
function wrap($xml) {
    return sprintf ( '<x>%s</x>', $xml );
}
function fix($xml) {
    return str_ireplace ( '"LoginId', "\" LoginId", $xml );
}

$xml = wrap ( fix ( $o->customerdata ) );
$sx = new SimpleXMLElement ( $xml );
$sx = ( array ) $sx;
$sx = $sx ['TPSession'];
foreach ( $sx as $row ) {
    var_dump ( ( array ) $row );
}
+1
source

All Articles