php xml 互相轉換

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   檔案   

正好昨天才做過類似的需求……幾行代碼就可以搞定。

如果你使用 curl 擷取的 xml data
$xml = simplexml_load_string($data);
$data[‘tk‘] = json_decode(json_encode($xml),TRUE);

如果是直接擷取 URL 資料的話
$xml = simplexml_load_file($data);
$data[‘tk‘] = json_decode(json_encode($xml),TRUE);

先把 simplexml 對象轉換成 json,再將 json 轉換成數組。

 

 

xml與數組互轉  

2007-12-18 12:29:37|  分類: Xml |舉報 |字型大小 訂閱

 

//如果亂碼的話更改header函數

<?php //header(‘Content-type: text/html;charset=utf-8‘);
class xmlarray
{

    private $xml = ‘‘;//用於讀取xml的變數
    private $data;    //產生的xml
    private $dom_tree;//xml分類樹
/**
   __construct僅用於讀取xml
*/
    function __construct($xml="")
    {
   if(empty($xml))
   {
    return null;
   }
   //$this->xml = $xml;
   else
   {
             $this->loadxml($xml);
   }
    }
/**
     裝載要處理的xml文檔也可以在初始化時裝載
*/
public function loadxml($filepath)
{  
      $handle = @fopen($filepath,"r");

         while (!feof($handle)&&$handle)
   {
              $xml_data .= fgets($handle, 4096);
         }
   $this->xml=$xml_data;
}
/**
     處理xml文檔
*/
    private function _struct_to_array($values, &$i)
    {
   $child = array();
   if (isset($values[$i][‘value‘])) array_push($child, $values[$i][‘value‘]);

   while ($i++ < count($values))
   {
    switch ($values[$i][‘type‘])
    {
     case ‘cdata‘:
      array_push($child, $values[$i][‘value‘]);
      break;

     case ‘complete‘:
      $name = $values[$i][‘tag‘];
      if(!empty($name))
      {
       $child[$name]= ($values[$i][‘value‘])?($values[$i][‘value‘]):‘‘;
       if(isset($values[$i][‘attributes‘]))
       {
        $child[$name] = $values[$i][‘attributes‘];
       }
      }
      break;

     case ‘open‘:
      $name = $values[$i][‘tag‘];
      $size = isset($child[$name]) ? sizeof($child[$name]) : 0;
      $child[$name][$size] = $this->_struct_to_array($values, $i);
     break;

     case ‘close‘:
      return $child;
      break;
    }
   }
   return $child;
    }
/**
    處理xml文檔,實際調用 _struct_to_array()處理
*/
    public function xml2array()
    {
        $xml    =& $this->xml;
        $values = array();
        $index = array();
        $array = array();
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parse_into_struct($parser, $xml, $values, $index);

        xml_parser_free($parser);
        $i = 0;
        $name = $values[$i][‘tag‘];
        $array[$name] = isset($values[$i][‘attributes‘]) ? $values[$i][‘attributes‘] : ‘‘;
        $array[$name] = $this->_struct_to_array($values, $i);
        return $array;
    }


    //以下為將數群組轉換成xml的代碼 使用dom
        /**
     讀取數組
         */
        public function array2xml($array){
            if(!is_array($array)){
                throw new Exception(‘array2xml requires an array‘, 1);
                unset($array);
            }
            if(!count($array)){
                throw new Exception(‘array is empty‘, 2);
                unset($array);
            }
           
            $this->data = new DOMDocument();         
            $this->dom_tree = $this->data->createElement(‘result‘);//預設要標籤
            $this->data->appendChild($this->dom_tree);
            $this->recurse_node($array, $this->dom_tree);
        }
       
        /**
             處理數組為xml
         */
        private function recurse_node($data, $obj){
            $i = 0;
            foreach($data as $key=>$value){
                if(is_array($value)){
                    //recurse if neccisary
                    $sub_obj[$i] = $this->data->createElement($key);//建立標籤
                    $obj->appendChild($sub_obj[$i]); //將標籤加入到$obj標籤下
                    $this->recurse_node($value, $sub_obj[$i]); //將值加入此標籤下
                } elseif(is_object($value)) {
                    //no object support so just say what it is
                    $sub_obj[$i] = $this->data->createElement($key, ‘Object: "‘ . $key . ‘" type: "‘ . get_class($value) . ‘"‘);
                    $obj->appendChild($sub_obj[$i]);
                } else {
                    //straight up data, no weirdness
                    $sub_obj[$i] = $this->data->createElement($key, $value);
      //如果是最後的節點,將節點名和內容建立
                    $obj->appendChild($sub_obj[$i]);
                }
                $i++;
            }
        }
       
        /**
       將數組儲存成xml檔案
         */
        public function saveXML($arraytoxml="")
   {
    if($arraytoxml=="")
    {
     $out = iconv("gbk","utf-8","請輸入將要儲存的檔案名稱");
     echo "<script>alert(‘$out‘)</script>";
    }
    else
    {
                 return $this->data->save($arraytoxml);
    }
        }
}
?>


將數群組轉換成xml檔案
<?php
   $test = array(
        ‘one‘=>‘number‘,
        ‘two‘=> array(
            ‘c‘=>1,
            ‘d‘=>2,
            ‘e‘=>3,
            ‘f‘=>4
        ),
        ‘three‘=>‘alpha‘
    );
   /*建立對象*/
   $xmlObj= new xmlarray();
   /*轉換*/
   $xml = $xmlObj->array2xml($test);
   /*輸出儲存*/
   $xmlObj->saveXML("a.xml");
   ?>


將xml解析為數組輸出
<?php
   /*建立對象*/
   $xmlObj    = new xmlarray();
   /*裝載*/
   $xml = $xmlObj->loadxml("a.xml");
   /*轉換*/
   $data=$xmlObj->xml2array();
   /*顯示*/
   print_r($data);
?>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.