PHP实现XML与数据格式进行转换类实例
本文实例讲述了PHP实现XML与数据格式进行转换类。分享给大家供大家参考。具体如下:
<?php
/**
*xml2array()willconvertthegivenXMLtexttoanarrayintheXMLstructure.
*Link:http://www.bin-co.com/php/scripts/xml2array/
*Arguments:$contents-TheXMLtext
*$get_attributes-1or0.Ifthisis1thefunctionwillgettheattributesaswellasthetagvalues-thisresultsinadifferentarraystructureinthereturnvalue.
*$priority-Canbe'tag'or'attribute'.Thiswillchangethewaytheresultingarraysturcture.For'tag',thetagsaregivenmoreimportance.
*Return:TheparsedXMLinanarrayform.Useprint_r()toseetheresultingarraystructure.
*Examples:$array=xml2array(file_get_contents('feed.xml'));
*$array=xml2array(file_get_contents('feed.xml',1,'attribute'));
*/
functionxml2array($contents,$get_attributes=1,$priority='tag'){
if(!$contents)returnarray();
if(!function_exists('xml_parser_create')){
//print"'xml_parser_create()'functionnotfound!";
returnarray();
}
//GettheXMLparserofPHP-PHPmusthavethismodulefortheparsertowork
$parser=xml_parser_create('');
xml_parser_set_option($parser,XML_OPTION_TARGET_ENCODING,"UTF-8");//http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($parser,trim($contents),$xml_values);
xml_parser_free($parser);
if(!$xml_values)return;//Hmm...
//Initializations
$xml_array=array();
$parents=array();
$opened_tags=array();
$arr=array();
$current=&$xml_array;//Refference
//Gothroughthetags.
$repeated_tag_index=array();//Multipletagswithsamenamewillbeturnedintoanarray
foreach($xml_valuesas$data){
unset($attributes,$value);//Removeexistingvalues,ortherewillbetrouble
//Thiscommandwillextractthesevariablesintotheforeachscope
//tag(string),type(string),level(int),attributes(array).
extract($data);//Wecouldusethearraybyitself,butthiscooler.
$result=array();
$attributes_data=array();
if(isset($value)){
if($priority=='tag')$result=$value;
else$result['value']=$value;//Putthevalueinaassocarrayifweareinthe'Attribute'mode
}
//Settheattributestoo.
if(isset($attributes)and$get_attributes){
foreach($attributesas$attr=>$val){
if($priority=='tag')$attributes_data[$attr]=$val;
else$result['attr'][$attr]=$val;//Setalltheattributesinaarraycalled'attr'
}
}
//Seetagstatusanddotheneeded.
if($type=="open"){//Thestartingofthetag'<tag>'
$parent[$level-1]=&$current;
if(!is_array($current)or(!in_array($tag,array_keys($current)))){//InsertNewtag
$current[$tag]=$result;
if($attributes_data)$current[$tag.'_attr']=$attributes_data;
$repeated_tag_index[$tag.'_'.$level]=1;
$current=&$current[$tag];
}else{//Therewasanotherelementwiththesametagname
if(isset($current[$tag][0])){//Ifthereisa0thelementitisalreadyanarray
$current[$tag][$repeated_tag_index[$tag.'_'.$level]]=$result;
$repeated_tag_index[$tag.'_'.$level]++;
}else{//Thissectionwillmakethevalueanarrayifmultipletagswiththesamenameappeartogether
$current[$tag]=array($current[$tag],$result);//Thiswillcombinetheexistingitemandthenewitemtogethertomakeanarray
$repeated_tag_index[$tag.'_'.$level]=2;
if(isset($current[$tag.'_attr'])){//Theattributeofthelast(0th)tagmustbemovedaswell
$current[$tag]['0_attr']=$current[$tag.'_attr'];
unset($current[$tag.'_attr']);
}
}
$last_item_index=$repeated_tag_index[$tag.'_'.$level]-1;
$current=&$current[$tag][$last_item_index];
}
}elseif($type=="complete"){//Tagsthatendsin1line'<tag/>'
//Seeifthekeyisalreadytaken.
if(!isset($current[$tag])){//NewKey
$current[$tag]=$result;
$repeated_tag_index[$tag.'_'.$level]=1;
if($priority=='tag'and$attributes_data)$current[$tag.'_attr']=$attributes_data;
}else{//Iftaken,putallthingsinsidealist(array)
if(isset($current[$tag][0])andis_array($current[$tag])){//Ifitisalreadyanarray...
//...pushthenewelementintothatarray.
$current[$tag][$repeated_tag_index[$tag.'_'.$level]]=$result;
if($priority=='tag'and$get_attributesand$attributes_data){
$current[$tag][$repeated_tag_index[$tag.'_'.$level].'_attr']=$attributes_data;
}
$repeated_tag_index[$tag.'_'.$level]++;
}else{//Ifitisnotanarray...
$current[$tag]=array($current[$tag],$result);//...Makeitanarrayusingusingtheexistingvalueandthenewvalue
$repeated_tag_index[$tag.'_'.$level]=1;
if($priority=='tag'and$get_attributes){
if(isset($current[$tag.'_attr'])){//Theattributeofthelast(0th)tagmustbemovedaswell
$current[$tag]['0_attr']=$current[$tag.'_attr'];
unset($current[$tag.'_attr']);
}
if($attributes_data){
$current[$tag][$repeated_tag_index[$tag.'_'.$level].'_attr']=$attributes_data;
}
}
$repeated_tag_index[$tag.'_'.$level]++;//0and1indexisalreadytaken
}
}
}elseif($type=='close'){//Endoftag'</tag>'
$current=&$parent[$level-1];
}
}
return($xml_array);
}
//ArraytoXML
classarray2xml{
public$output="<?xmlversion=\"1.0\"encoding=\"utf-8\"?>\n";
public$sub_item=array();
publicfunction__construct($array){
$sub_item=array();
$this->output.=$this->xmlmake($array);
}
publicfunctionxmlmake($array,$fk=''){
$xml='';
global$sub_item;
foreach($arrayas$key=>$value){
if(is_array($value)){
if(is_numeric($key)){
$this->sub_item=array_merge($this->sub_item,array($fk));
$xml.="<{$fk}>".$this->xmlmake($value,$key)."</{$fk}>";
}else{
$xml.="<{$key}>".$this->xmlmake($value,$key)."</{$key}>";
}
}else{
$xml.="<{$key}>{$value}</{$key}>\n";
}
}
return$xml;
}
publicfunctionoutput(){
foreach($this->sub_itemas$t){
$this->output=str_replace("<{$t}><{$t}>","<{$t}>",$this->output);
$this->output=str_replace("</{$t}></{$t}>","</{$t}>",$this->output);
}
return$this->output;
}
}
希望本文所述对大家的php程序设计有所帮助。