在将xml转换为php数组时,空xml字段会生成一个空数组而不是空字符串


On converting xml to php array empty xml fields producing an empty array rather than empty string

我正在使用一段漂亮的短代码将我的xml字符串转换为php数组

$products = json_decode(json_encode(simplexml_load_string($products_xml)),TRUE);

这一切都很好,除了当xml字段为空时——当我得到一个空数组而不是字符串时——当写入SQL数据库时,我看到的是字符串"array"而不是空字段。

有没有一种很好的方法可以用php实现这一点?


与此同时,我设法用这个代码解决了问题:

$products = json_decode(str_replace('{}', '""', json_encode(simplexml_load_string($products_xml))),TRUE);

如果json_encoded xml中的任何内容字段包含"{}",则此代码将中断。这件事发生在我身上,我正在制定一个解决方案来防止这种情况的发生。

function removeElementArrays($array) {
        $temp = [];
        foreach ($array as $record){
            $ta = [];
            foreach ($record as $k=>$v) {
                if (is_array($v)) {
                    $ta[$k]='';
                } else {
                    $ta[$k]=$v;
                }
            }
            array_push($temp, $ta);
        }
        return $temp;
    }