在 PHP 中将带有 XML 数据的 stdClass 对象转换为数组


convert stdClass object with XML data to array in PHP

给定此对象:

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

如何使用 PHP 将此 XML 数据转换为数组?

只需将其转换为数组:

$arr = (array) $obj;

问题中的 XML 数据无效。

  1. 它没有根元素
  2. CustomerId="1234567"LoginId="1234567" 中断 xml 解析

你需要把它包装成根元素,解决属性问题,而不是你可以使用简单的xml解析器来生成可以转换为数组的对象。

$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 );
}

如果我知道您想将对象元素中包含的字符串转换为数组,换句话说,将 xml 字符串转换为数组。

这就是你要找的...

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

按照此页面上的示例进行操作。