• 技术文章 >后端开发 >php教程

    PHP 创建XML文档

    巴扎黑巴扎黑2016-11-23 09:56:33原创568
    <?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核实处理。
    上一篇:phpize是什么 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 设计API接口时,要注意这些地方!• PHP8.3要有新函数了!(json_validate函数说明)• 一文详解PHP实现职责链设计模式(附代码示例)• 手写PHP API框架(二)之Composer的安装使用• 聊聊PHP escapeshellarg函数使用的中文问题
    1/1

    PHP中文网