数组转XML

发表日期:2019-01-05 23:08:27 | 来源: | | 浏览(803) 分类:PHP杂项

<?php


/**

 * 数组转XML

 */

class ArrayToXML

{


private $xmlString;


private function header()

{

$this->xmlString .= '<?xml version="1.0" encoding="utf-8" ?>';

$this->xmlString .= '<root>';

}


private function footer()

{

$this->xmlString .= '</root>';

}

public function encode($array)

{


header('Content-type:text/xml;');


$this->header();


$this->paser($array);


$this->footer();


return $this->xmlString ;

}


private function paser($array)

{

foreach ($array as $key => $value)

{

$tag = is_numeric($key) ? 'item' : $key;

$this->xmlString .= "<$tag";



if (is_array($value))

{

if (isset($value['id'])) $this->xmlString .= " id=\"{$value['id']}\"";

$this->xmlString .= ">";


$this->paser($value);

}

else

{

$this->xmlString .= ">";


$this->xmlString .= $value;

}


$this->xmlString .= "</$tag>";

}

}

}


$array = array(

'code' => 200,

'message' => 'succeess',

'data' => array(

array(

'id' => 1,

'title' => 'demo2',

),

array(

'id' => 2,

'title' => 'demo3',

)

)

);



$xml = new ArrayToXML;


echo $xml->encode($array);

?>

集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。