日期:2014-05-16  浏览次数:20404 次

xmltojson中遇到的CDATA变空以及json_encode成unicode的解决方法
function xml_to_json($source) {
if(is_file($source)){ //传的是文件,还是xml的string的判断
$xml_array=simplexml_load_file($source);
}else{
$source =uncdata($source) ;

$xml_array=simplexml_load_string($source);

}
$json = json_encode($xml_array); //php5,以及以上,如果是更早版本,请查看JSON.php
return decodeUnicode($json);
}
//处理CDATA
function uncdata($xml)
    {
        // States:
        //
        //     'out'
        //     '<'
        //     '<!'
        //     '<!['
        //     '<![C'
        //     '<![CD'
        //     '<![CDAT'
        //     '<![CDATA'
        //     'in'
        //     ']'
        //     ']]'
        //
        // (Yes, the states a represented by strings.)
        //

        $state = 'out';

        $a = str_split($xml);

        $new_xml = '';

        foreach ($a AS $k => $v) {

            // Deal with "state".
            switch ( $state ) {
                case 'out':
                    if ( '<' == $v ) {
                        $state = $v;
                    } else {
                        $new_xml .= $v;
                    }
                break;

                case '<':
                    if ( '!' == $v  ) {
                        $state = $state . $v;
                    } else {
                        $new_xml .= $state . $v;