简体   繁体   English

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

[英]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? 如何使用PHP将此XML数据转换为数组?

只需将其转换为数组:

$arr = (array) $obj;

Xml data in the question is not valid. 问题中的Xml数据无效。

  1. It has no root element 它没有根元素
  2. CustomerId="1234567"LoginId="1234567" breaks xml parsing CustomerId =“1234567”LoginId =“1234567”打破xml解析

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. 您需要将其包装到根元素中,解决属性问题,而不是使用简单的xml解析器来生成可以转换为数组的对象。

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

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. 如果我理解你想将包含在object元素中的字符串转换为数组,换句话说,将xml字符串转换为数组。

This is what you looking for... 这就是你要找的......

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

Follow the example on this page. 按照此页面上的示例操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM