Home >Backend Development >PHP Tutorial >Create XML document with PHP
<?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()); ?>
Instructions:
$dom = new DOMDocument("1.0", "UTF-8"); Create DOM and specify its encoding method. The default encoding method is UTF-8. This line of sample code is equivalent to: $dom = new DOMDocument(); using the default encoding.
Create element: $phpedu = $dom -> createElement("phpedu"); Create an element with the name: phpedu; $title = $dom -> createElement("title", "PHP100"); Create an element and Specify its value.
Add elements to the parent node: $dom -> appendChild($phpedu);
Set the attributes of the element: $item -> setAttribute("type", "text"); You can add multiple attributes to an element .
One more thing: I hope it will be helpful to you. Code source: www.php100.com =^_^=