萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> PHP cdata 處理(詳細介紹)

PHP cdata 處理(詳細介紹)

之前為項目趕進度用php 的simplexml來解析 xml, 當時發現 simplexml不支持<![CDATA標簽, 所有處於這個標簽內的值都沒有辦法取到  

當時在網上找了一個CDATA的轉換器, 修改之後, 將CDATA標簽給過濾掉。如下

復制代碼 代碼如下:
 // 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;
                        $state = 'out';
                    }
                break;
                 case '<!':
                    if ( '[' == $v  ) {
                        $state = $state . $v;
                    } else {
                        $new_xml .= $state . $v;
                        $state = 'out';
                    }
                break;
                case '<![':
                    if ( 'C' == $v  ) {
                        $state = $state . $v;
                    } else {
                        $new_xml .= $state . $v;
                        $state = 'out';
                    }
                break;
                case '<![C':
                    if ( 'D' == $v  ) {
                        $state = $state . $v;
                    } else {
                        $new_xml .= $state . $v;
                        $state = 'out';
                    }
                break;
                case '<![CD':
                    if ( 'A' == $v  ) {
                        $state = $state . $v;
                    } else {
           
copyright © 萬盛學電腦網 all rights reserved