Blog : SimpleXMLElement::addChild

SimpleXMLElement::addChild

Exemple #1 Ajoute des attributs et des enfants à un élément SimpleXML

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&#xD3;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>


Voir aussi

  SimpleXMLElement::addAttribute() - Ajoute un attribut à l'élément SimpleXML
  Utilisation de base SimpleXML

add a note
User Contributed Notes 7 notes

up

down

7

frosty dot z at freesbee dot fr ¶

9 months ago

To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

$xmlelement->value = 'my value < > &';// results in my value < > &?>
instead of doing :

$xmlelement->addChild('value', 'my value < > &');// results in my value < > & (invalid XML)?>
See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

Here is a class with more functions for SimpleXMLElement :

/**
 *
 * 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);
  }
  }
  }
} ?>

If you're looking for a way to append children you may be interested in this:

$x = new SimpleXMLElement(''); $f1 = new SimpleXMLElement('alpha'); $f2 = new SimpleXMLElement('beta'); $f3 = new SimpleXMLElement('gamma'); $x->{$f1->getName()} = $f1; $x->{$f2->getName()}[] = $f2; $x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
  var_dump($foo);
} ?>

Here's my solution for creating XML from Multidimensional Array.
//DATA
  $xmlDAta = array(
  array(
  "name"  => "nameVal",
  "value" => "valVal",
  "css"  => "cssVal"
  ),
  array(
  "name"  => "name1Val",
  "value" => "val1Val",
  "css"  => "css1Val"
  ),
  "tname" => array(
  array(
  "iTname"  => "iTname",
  "iTname2"  => "iTname1",
  "iTname2"  => "iTname2",
  "iTbname3" => array(
  "iiTbname"  => "tbName",
  "iiTbname1" => "tbName1",
  ),
  ),
  ),
  "tdata" => "otheerDAta"
  );

  /**
  * Create XML using string or array
  *
  * @param mixed $data input data
  * @param SimpleXMLElement $xml
  * @param string $child name of first level child
  *
  * @return adding Xml formated data into SimpleXmlElement
  */function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
  {

  foreach($data as $key => $val) {
  if(is_array($val)) {

  if(is_numeric($key)) {
  $node  = $xml->addChild($child);
  $nodes = $node->getName($child);
  } else {

  $node  = $xml->addChild($key);
  $nodes = $node->getName($key);
  }

  $node->addChild($nodes, self::data2Xml($val, $node));
  } else {
  $xml->addChild($key, $val);
  }
  }

  }//Use

  $xml  = new SimpleXMLElement("");
  Util::data2XML($xmlDAta, $xml, "Items");?>

Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.

up

down

0

felipenmoura at gmail dot com ¶

2 years ago

This method returns a reference to the specific SimpleXMLElement.
If you use:
  $xml= new SimpleXMLElement('');
  $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
  $son= $xml->father->addChild('son'); // uses the first father tag
  $son['name']= 'first son';
  $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
  $otherSon['name']= 'second son';
 
  echo htmlentities($xml->asXML());?>
The result will be