本文執行個體講述了php實現將數群組轉換為XML的方法。分享給大家供大家參考。具體如下:
1. php代碼如下:
<?phpclass A2Xml { private $version = '1.0'; private $encoding = 'UTF-8'; private $root = 'root'; private $xml = null; function __construct() { $this->xml = new XmlWriter(); } function toXml($data, $eIsArray=FALSE) { if(!$eIsArray) { $this->xml->openMemory(); $this->xml->startDocument($this->version, $this->encoding); $this->xml->startElement($this->root); } foreach($data as $key => $value){ if(is_array($value)){ $this->xml->startElement($key); $this->toXml($value, TRUE); $this->xml->endElement(); continue; } $this->xml->writeElement($key, $value); } if(!$eIsArray) { $this->xml->endElement(); return $this->xml->outputMemory(true); } }}$res = array( 'hello' => '11212', 'world' => '232323', 'array' => array( 'test' => 'test', 'b' => array('c'=>'c', 'd'=>'d') ), 'a' => 'haha');$xml = new A2Xml();echo $xml->toXml($res);
2. 運行效果如下圖所示:
PS:這裡再為大家提供幾款關於xml操作的線上工具供大家參考使用:
線上XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
線上格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
希望本文所述對大家的php程式設計有所協助。