Listed examples may include example.php,
which refers to the XML string found in the first example
of the basic usage guide.
Example #1 Add attributes and children to a SimpleXML element
<?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.');
The above example will output
something similar to:
<?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>
Here is a class with more functions for SimpleXMLElement :
<?php
/**
*
* Extension for SimpleXMLElement
* @author Alexandre FERAUD
*
*/
class ExSimpleXMLElement extends SimpleXMLElement
{
/**
* Add CDATA text in a node
* @param string $cdata_text The CDATA value to add
*/
private function addCData($cdata_text)
{
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
/**
* Create a child with CDATA value
* @param string $name The name of the child element to add.
* @param string $cdata_text The CDATA value of the child element.
*/
public function addChildCData($name,$cdata_text)
{
$child = $this->addChild($name);
$child->addCData($cdata_text);
}
/**
* Add SimpleXMLElement code into a SimpleXMLElement
* @param SimpleXMLElement $append
*/
public function appendXML($append)
{
if ($append) {
if (strlen(trim((string) $append))==0) {
$xml = $this->addChild($append->getName());
foreach($append->children() as $child) {
$xml->appendXML($child);
}
} else {
$xml = $this->addChild($append->getName(), (string) $append);
}
foreach($append->attributes() as $n => $v) {
$xml->addAttribute($n, $v);
}
}
}
}
?>
For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.