編程以來一直用網易有道詞典查單詞、翻譯;最近一直在看英文方面的資料,因而愈來愈對有道詞典(劃詞、廣告,原本想轉靈格斯的,但靈格斯沒有android版)不滿意,一番試用後決定轉bing詞典,因而想把有道單詞本里的單詞導出php
再導入bing詞典,但操做後才發現有道詞典導出的xml和bing詞典的xml格式和節點不同,但我執意要換爲bing詞典,沒辦法只好本身本身動手寫一個php將有道的xml轉爲bing詞典能導入的xml。android
數組轉xml是在網上找的,雖然簡單,但功能還行。編程
下面是代碼:數組
<?php // 有道詞典xml 轉爲bing詞典能夠導入的xml /** * 把數組轉化爲xml,數字索引只支持一維,數字索引和字符索引不能混合 * * @param array $array * @return string */ function arrayToXML($array) { $str_xml = ""; if (is_array($array) && !empty($array)) { $has_number_key = false; foreach ($array as $key => $value) { $parent_key = @func_get_arg(2); if (is_integer($key)) { $has_number_key = true; if (is_integer($parent_key)) { throw new Exception('數字索引只支持一維'); } if (empty($parent_key)) { $parent_key = $key; } else { if ($parent_key{strlen($parent_key) - 1} == 's') { $parent_key = substr($parent_key, 0, strlen($parent_key) - 1); } } $str_xml .= "<$parent_key>" . arrayToXML($value,$key, $parent_key) . "</$parent_key>"; } else { if ($has_number_key) { throw new Exception('數字索引和字符索引不能混合'); } $parent_key = $key; $str_xml .= "<$key>" . arrayToXML($value,$key, $parent_key) . "</$key>"; } } } else { $key = func_get_arg(1); if (strpos($array, '<') !== false) { return '<![CDATA[' . $array . ']]>'; } if (is_array($array) && empty($array)) { return ''; } return $array ; } return $str_xml; } $xmlObject = simplexml_load_file("youdao.xml"); $item = $xmlObject->item; $datas = array(); for($i=0;$i<$item->count();$i++){ $trans = trim(strval($item[$i]->trans)); if(!empty($trans)){ //去除沒有解釋的單詞、不然導入bing詞典報錯 $datas['Phrases'][$i]['Eng']= strval($item[$i]->word);//讀取xml每項值 $datas['Phrases'][$i]['Phonetic']= strval($item[$i]->phonetic); $datas['Phrases'][$i]['Defi']= str_replace(array(';','\n'),array(';',''),strval($item[$i]->trans)); //中文分號替換 $datas['Phrases'][$i]['Date']= date("Y-m-d H:i:s"); } } //構建xml $xml = '<?xml version="1.0"?><FCVocaPhraseList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'; $xml .= arrayToXML($datas); $xml .= '</FCVocaPhraseList>'; header('Content-Type: text/xml'); echo $xml;