例子
現在有一個uncletoo.xml的設定檔,格式如下:
<h6>Step 1: XML File</h6>
<?xml version='1.0'?>
<moleculedb>
<molecule name='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
<molecule name='Parvez'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>
1、讀XML檔案內容,並儲存到字串變數中
下面我們使用PHP內建的file_get_contents()函數將檔案內容讀取到一個字串變數中:
$xmlfile = file_get_contents($path);
此時$xmlfile變數的值如下:
2、將字串轉換為對象
這一步我們將使用simplexml_load_string()函數,將上一步得到的字串轉換為對象(Object):
$ob= simplexml_load_string($xmlfile);
此時$ob的值如下:
3、將對象轉換為JSON
上一步轉換成對象後,現在,我們要將對象轉換成JSON格式字串:
$json = json_encode($ob);
此時$json變數的值如下:
4、解析JSON字串
這也是最後一步了,我們需要將JSON格式的字串轉換為我們需要的數組:
$configData = json_decode($json, true);
現在$configData裡儲存的資料就是我麼最後要得到的數組,如下:
完整轉碼:
| 代碼如下 |
複製代碼 |
<?php $xmlfile = file_get_contents($path); $ob= simplexml_load_string($xmlfile); $json = json_encode($ob); $configData = json_decode($json, true); ?>
|
下面為網上整理的xml轉換數組函數
例子一,將XML轉成數組
| 代碼如下 |
複製代碼 |
如果你使用 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 轉 數組, 包括根鍵 function xml_to_array( $xml ) { $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/"; if(preg_match_all($reg, $xml, $matches)) { $count = count($matches[0]); for($i = 0; $i < $count; $i++) { $subxml= $matches[2][$i]; $key = $matches[1][$i]; if(preg_match( $reg, $subxml )) { $arr[$key] = xml_to_array( $subxml ); }else{ $arr[$key] = $subxml; } } } return $arr; } // Xml 轉 數組, 不包括根鍵 function xmltoarray( $xml ) { $arr = xml_to_array($xml); $key = array_keys($arr); return $arr[$key[0]]; } |
例子三
| 代碼如下 |
複製代碼 |
function simplexml_obj2array($obj){ if ($obj instanceof SimpleXMLElement) { $obj = (array)$obj; } if (is_array($obj)) { $result = $keys = array(); foreach( $obj as $key=>$value) { isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1); if( $keys[$key] == 1 ) { $result[$key] = simplexml_obj2array($value); } elseif( $keys[$key] == 2 ) { $result[$key] = array($result[$key], simplexml_obj2array($value)); } else if( $keys[$key] > 2 ) { $result[$key][] = simplexml_obj2array($value); } } return $result; } else { return $obj; } } $xml=simplexml_load_file("D:/ www.111cn.net /lib/books.xml"); $rss = simplexml_obj2array($xml); |