PHP之XML: simplexml_load_string奇怪的问题

看代码:

$xmlStr = <<<XML
<?xml version='1.0'?>
<response>
<amount>-2</amount>
<currency>USD</currency>
<transaction_id></transaction_id>
</response>
XML;
$result = simplexml_load_string($xmlStr);
var_dump($result);

// output
/*

object(SimpleXMLElement)#1 (3) {
["amount"]=>
string(2) "-2"
["currency"]=>
string(3) "USD"
["transaction_id"]=>
object(SimpleXMLElement)#2 (0) {
}
}
*/

simplexml_load_string在处理"<transaction_id></transaction_id>"时,返回了一个空simplexml对象,而不是''空字符串.

这个在给后续程序转换xml对象为数组时带来了一点麻烦, 如果没有空simplexml对象的话,可以很简单的处理:

function obj2arr($obj) {
return @json_decode(@json_encode($obj), 1);
}

但是如果包含空simplexml对象的话,需要用更安全的写法:

/**
* 把对象转换成数组
* @param object $object 要转换的对象
* @return array
*/
function objectToArray($object) {
if( count($object)==0 ) return trim((string)$object);
$result = array();
$object = is_object($object) ? get_object_vars($object) : $object;
foreach ($object as $key => $val) {
$val = (is_object($val) || is_array($val)) ? objectToArray($val) : $val;
$result[$key] = $val;
}
return $result;
}

其他相关资料:

PHP里simplexml_load_string函数一个容易犯晕的地方

convert simplexml object to array sets: http://fayaa.com/code/view/7350/




posted on 2011-12-26 12:01  DavidYanXW  阅读(6387)  评论(0编辑  收藏  举报