SimpleXMLElement::addChild
SimpleXMLElement::addChild
(PHP 5 >= 5.1.3, PHP 7)
SimpleXMLElement :: addChild - 向XML节点添加一个子元素
描述
public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )
向该节点添加一个子元素并返回该子元素的SimpleXMLElement。
参数
name
要添加的子元素的名称。
value
如果指定,则为子元素的值。
namespace
如果指定,则为子元素所属的名称空间。
返回值
所述的addChild
方法返回表示添加到XML节点的孩子SimpleXMLElement对象。
例子
注意
:列出的示例可能包含example.php
,它引用基本使用指南第一个示例中的XML字符串。
示例#1 将属性和子项添加到SimpleXML元素
<?php
include 'example.php';
$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(
?>
上面的例子会输出:
<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
<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>
<movie>
<title>PHP2: More Parser Stories</title>
<plot>This is all about the people who make it work.</plot>
<characters>
<character>
<name>Mr. Parser</name>
<actor>John Doe</actor>
</character>
</characters>
<rating type="stars">5</rating>
</movie>
</movies>
扩展内容
- SimpleXMLElement :: addAttribute() - 向SimpleXML元素添加一个属性
← SimpleXMLElement::addAttribute
SimpleXMLElement::asXML →