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/





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM