PHP SimpleXMLElement::addChild SimpleXML 函数



  • 定义和用法

    SimpleXMLElement::addChild - 将子元素添加到XML节点
  • 版本支持

    PHP4 PHP5 PHP7
    不支持 v5.1.3+支持 支持
  • 语法

    SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )
    
    将属性添加到SimpleXML元素。
  • 参数

    参数 必需的 描述
    name 要添加的子节点的名称。。
    value 子节点的值。
    namespace 如果指定,则子节点所属的命名空间。
  • 返回值

    addChild方法返回一个SimpleXMLElement对象,该对象表示添加到XML节点的子级。
  • 示例

    <?php
    header('Content-Type: text/xml; charset=UTF-8');
    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
    <movies>
     <movie>
      <title>PHP: Behind the Parser</title>
      <characters>
       <character>
        <name>Ms. Coder</name>
        <actor>Onlivia Actora</actor>
       </character>
       <character>
        <name>Mr. Coder</name>
        <actor>El ActÓr</actor>
       </character>
      </characters>
      <plot>
       So, this language. It's like, a programming language. Or is it a
       scripting language? All is revealed in this thrilling horror spoof
       of a documentary.
      </plot>
      <great-lines>
       <line>PHP solves all my web problems</line>
      </great-lines>
      <rating type="thumbs">7</rating>
      <rating type="stars">5</rating>
     </movie>
    </movies>
    XML;
    
    $sxe = new SimpleXMLElement($xmlstr);
    $sxe->addAttribute('type', 'documentary');
    
    $movie = $sxe->addChild('movie');
    $movie->addChild('title', 'PHP2: More Parser Stories');
    $movie->addChild('plot', 'This is all about the people who make it work.');
    
    $characters = $movie->addChild('characters');
    $character  = $characters->addChild('character');
    $character->addChild('name', 'Mr. Parser');
    $character->addChild('actor', 'John Doe');
    
    $rating = $movie->addChild('rating', '5');
    $rating->addAttribute('type', 'stars');
    
    echo $sxe->asXML();
    
  • 相关函数

    SimpleXMLElement::addAttribute() - 向SimpleXML元素添加属性