convert stdClass object with XML data to array in PHP

213

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?

71

Answer

Solution:

Simply cast it to array:

$arr = (array) $obj;
742

Answer

Solution:

Xml data in the question is not valid.

  1. It has no root element
  2. CustomerId="1234567"LoginId="1234567" breaks xml parsing

You need to wrap it into root element , resolve attribute issue, than you can use simple xml parser to generate object that can be converted to 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 );
}
105

Answer

Solution:

If I understand you want to convert the string contained into the object element to an array, in other words, convert an xml string to an array.

This is what you looking for...

http://php.net/manual/en/function.simplexml-load-string.php

Follow the example on this page.

People are also looking for solutions to the problem: Regex to ignore accents? PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.