PHP 创建XML文档

巴扎黑
巴扎黑 原创
2016-11-23 09:56:33 649浏览
<?php
// 创建DOM
$dom = new DOMDocument("1.0", "UTF-8");
$dom -> formatOutput = true;
// 创建元素
$phpedu = $dom -> createElement("phpedu");
// 添加元素到父节点
$dom -> appendChild($phpedu);
$title = $dom -> createElement("title", "PHP100");
$phpedu -> appendChild($title);
// 创建元素
$item = $dom -> createElement("item");
// 设置属性
$item -> setAttribute("type", "text");
// 设置属性
$item -> setAttribute("name", "item");
// 添加元素到父节点
$phpedu -> appendChild($item);
$php = $dom -> createElement("contents", "PHP");
$php -> setAttribute("type", "text");
$item -> appendChild($php);
$sql = $dom -> createElement("contents", "SQL");
$item -> appendChild($sql);
$linux = $dom -> createElement("contents", "Linux");
$item -> appendChild($linux);
$apache = $dom -> createElement("contents", "Apache");
$item -> appendChild($apache);
$address = $dom -> createElement("Address", "www.php100.com");
$address -> setAttribute("type", "URL");
$phpedu -> appendChild($address);
echo htmlspecialchars($dom -> saveXML());
?>

说明:

$dom = new DOMDocument("1.0", "UTF-8");创建DOM并指定其编码方式,默认编码方式是UTF-8。本行示例代码等价于:$dom = new DOMDocument();使用默认编码方式。

创建元素:$phpedu = $dom -> createElement("phpedu");创建元素,名称是:phpedu;$title = $dom -> createElement("title", "PHP100");创建元素并指定其值。

添加元素到父节点:$dom -> appendChild($phpedu);

设置元素的属性:$item -> setAttribute("type", "text");可以为一个元素添加多个属性。

多说一句:希望对您有所帮助,代码来源:www.php100.com =^_^=


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。