PHP SimpleXMLElement数组:空值 [英] php simpleXMLElement to array: null value
问题描述
我有以下XML:
<account>
<id>123</id>
<email></email>
<status>ACTIVE</status>
</account>
我想把它作为数组变量.因此,我用$xml = simplexml_load_file()
进行了阅读.将simpleXMLElement转换为关联数组的最简单方法是使用以下方法进行研磨:json_decode(json_encode((array) $xml),1);
I want to have it as an array variable. Therefore I read it with $xml = simplexml_load_file()
. The simplest way to convert simpleXMLElement to an associative array I know is to grind it with: json_decode(json_encode((array) $xml),1);
问题是我不想将email
键作为空数组,而希望将其作为NULL
值.作为SimpleXMLElement,它看起来像:
The problem is that I don't want to get the email
key as an empty array, but rather as a NULL
value. As SimpleXMLElement, it looks like:
public 'email' =>
object(SimpleXMLElement)[205]
在数组中看起来像这样:
whereas in array it looks like:
'email' =>
array (size=0)
empty
我想得到:
'email' => NULL
我想到的唯一实现此方法的方法是遍历所有元素,并将空数组替换为null值.问题是我的XML更大(上面只是为了解释问题),我不得不迭代很多XML元素(这将是手动工作-我正在寻找自动的东西).也许我缺少其中一个功能的某些选项...或者也许还有另一个技巧可以做到这一点?
The only way to achieve this I thought of is iterate through all elements and replace empty array with null value. The problem is that my XML is way bigger (above is just to explain the problem) and I'd have to iterate a lot of XML elements (and this would be manual work - I'm looking for something automatic). Maybe I'm missing some options in one of the functions... or maybe there's another trick to do this?
推荐答案
我无法添加评论,但是我认为这对您有用,它应该比正则表达式或循环更快:
I cannot add a comment, but I think this will work for you, it should be faster then a regex or a loop:
//after you json_encode, before you decode
$str = str_replace(':[]',':null',json_encode($array));
JSON中的空数组由"[]
"表示.有时,将数组解析为对象,在这种情况下(或作为后备),您也可以替换":{}
".
An empty array in JSON is represented by "[]
". Sometimes the arrays are parsed as objects, in that case (or as a fallback) you can replace ":{}
" too.
这篇关于PHP SimpleXMLElement数组:空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!