使用PHP创建XML格式文档
发现一种实用的方案,直接贴上代码
header('content-type:text/html;charset=utf-8');
class DomXml
{
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);
}
}
}
//xml文档创建 填充
$res = array('version' => $version, 'url' => base64_encode($url), 'md5' => base64_encode($md5), 'description' => base64_encode($description), 'array' => array('timestamp' => '1458703564', 'lastmod' => array('time' => '2016', 'operator' => 'Y')), 'code' => '15234');
$xml = new DomXml();
echo $xml->toXml($res);
die;