【发布时间】:2019-08-21 09:29:52
【问题描述】:
我需要将 JSON 对象转换为 XML 文档。我使用this class,它做得很好。
问题是,有时我的 JSON 对象的属性会在类中引发异常,当元素名称 (W3C) 非法时,例如此输入:
{"first":"hello","second":{"item1":"beautiful","$item2":"world"}}
标签名称中有非法字符。 tag: $item2 in node: second
触发的函数是:
/*
* 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;
}
然后我想做的是在将 JSON 输入转换为 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);
我怎么能这样做?谢谢!
【问题讨论】:
-
不确定您想要什么,删除
"$xxx":"zzz"中的$?试试preg_replace('~(")\$(\w+":")~', '$1$2', $text)。 -
@WiktorStribiżew:问题已更新
-
我建议更改课程本身。当您拥有
{"item1":"beautiful","$item1":"world"}时,更改源数据可能会导致问题,因为这会创建两个带有item1的项目,而这两个项目在数组中会被覆盖,并且您最终会在输出中得到一个值。