duc*_*cin 9 php xml associative-array
我有以下XML:
<account>
<id>123</id>
<email></email>
<status>ACTIVE</status>
</account>
Run Code Online (Sandbox Code Playgroud)
我想把它作为一个数组变量.因此我读了它$xml = simplexml_load_file().将simpleXMLElement转换为关联数组的最简单方法是我用以下方法来研磨它:json_decode(json_encode((array) $xml),1);
问题是我不希望将email密钥作为空数组获取,而是作为NULL值.作为SimpleXMLElement,它看起来像:
public 'email' =>
object(SimpleXMLElement)[205]
Run Code Online (Sandbox Code Playgroud)
而在数组中它看起来像:
'email' =>
array (size=0)
empty
Run Code Online (Sandbox Code Playgroud)
我想得到:
'email' => NULL
Run Code Online (Sandbox Code Playgroud)
实现这一点的唯一方法我想到的是遍历所有元素并用空值替换空数组.问题是我的XML更大(上面只是解释问题)而且我必须迭代很多XML元素(这将是手工工作 - 我正在寻找自动化的东西).也许我错过了其中一个功能中的一些选项...或者可能还有另一个技巧可以做到这一点?
我无法添加评论,但我认为这对您有用,它应该比正则表达式或循环更快:
//after you json_encode, before you decode
$str = str_replace(':[]',':null',json_encode($array));
Run Code Online (Sandbox Code Playgroud)
JSON中的空数组由" []" 表示.有时,数组被解析为对象,在这种情况下(或作为后备),您也可以替换" :{}".