简体   繁体   English

如果它们与正则表达式模式不匹配,如何深度重命名数组键

[英]how to deep rename array keys if they don't match a regex pattern

I need to convert a JSON object to an XML document. 我需要将JSON对象转换为XML文档。 I use this class that does the job quite well. 我用这个班做得很好。

Problem is, sometimes my JSON object has attributes that throw an exception with the class, when element names are (W3C) illegal, like for this input: 问题是,当元素名称(W3C)非法时,有时我的JSON对象具有会引发类异常的属性,例如此输入:

{"first":"hello","second":{"item1":"beautiful","$item2":"world"}}

Illegal character in tag name. 标签名称中的字符非法。 tag: $item2 in node: second 标签:$ item2在节点:第二

The function that fires that is : 触发的函数是:

/*
 * Check if the tag name or attribute name contains illegal characters
 * Ref: http://www.w3.org/TR/xml/#sec-common-syn
 */
private static function isValidTagName($tag){
    $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
    return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
}

What I would then like to do is to "clean" my JSON input before converting it to an XML. 然后,我想做的是在将JSON输入转换为XML之前对其进行“清理”。

I thus need to have a function that would reformat the input data BEFORE converting it to XML. 因此,我需要有一个在将输入数据转换为XML之前重新格式化输入数据的功能。

function clean_array_input($data){
    //recursively clean array keys so they are only allowed chars
}

$data = json_decode($json, true);
$data = clean_array_input($data);

$dom = WPSSTMAPI_Array2XML::createXML($data,'root','element');
$xml = $dom->saveXML($dom);

How could I do that ? 我该怎么办? Thanks ! 谢谢 !

I think what you want is something like this. 我认为您想要的是这样的东西。 Create a new empty array, loop recursively through your data and filter keys. 创建一个新的空数组,递归遍历数据和过滤键。 At the end return new array. 最后返回新数组。 To prevent duplicate keys we will use uniqid. 为了防止重复的键,我们将使用uniqid。

function clean_array_input($data){

    $cleanData = [];
    foreach ($data as $key => $value) {

        if (is_array($value)) {
            $value = clean_array_input($value);
        }

        $key = preg_replace("/[^a-zA-Z0-9]+/", "", $key);
        if (isset($cleanData[$key])) {
            $key = $key.uniqid();
        }

        $cleanData[$key] = $value;
    }

    return $cleanData;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM