PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

SimpleXMLElement->asXML()> <SimpleXMLElement->addAttribute()
Last updated: Fri, 14 Nov 2008

view this page in

SimpleXMLElement->addChild()

(No version information available, might be only in CVS)

SimpleXMLElement->addChild() Ajoute un élément enfant au noeud XML

Description

SimpleXMLElement
SimpleXMLElement addChild ( string $name [, string $value [, string $namespace ]] )

Ajoute un élément enfant au noeud et retourne un SimpleXMLElement de l'enfant.

Liste de paramètres

name

Le nom de l'élément enfant à ajouter.

value

Si spécifié, la valeur de l'élément enfant.

namespace

Si spécifié, l'espace de nom auquel l'élément enfant appartient.

Valeurs de retour

La méthode addChild retourne un objet SimpleXMLElement représentant l'enfant à ajouter au noeud XML.

Exemples

Exemple #1 Ajoute des attributs et des enfants à un élément 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();

?>



add a note add a note User Contributed Notes
SimpleXMLElement->addChild()
davedx at gmail dot com
29-Oct-2008 11:48
As noted by zspencer at zacharyspencer dot com, addChild with an empty string causes a redundant node to be added. This was screwing up our web services xml->JSON conversion - the following hack seems to fix it, use at your own risk...

<?php
   
if($sv == null)
    {
       
$child = $node->addChild($k, '<blank>');
       
$child = '';
    }
    else
    {
       
$node->addChild($k, $sv);
    }
?>
Donet
02-Oct-2008 10:11
I found this easy way to create a CDATA section as child value:

I extend the class SimpleXMLElement:

<?php
class SimpleXMLExtended extends SimpleXMLElement
{
  public function
addCData($cdata_text)
  {
   
$node= dom_import_simplexml($this);
   
$no = $node->ownerDocument;
   
$node->appendChild($no->createCDATASection($cdata_text));
  }
}
?>

Then in the main code:

<?php
$xml
= new SimpleXMLExtended('<?xml version = "1.0" encoding = "UTF-8"?><root></root>');
$mynode = $xml->addChild("myname");
$mynode->addCData("my name contains everything I want &%<>");
echo
$xml->asXml();
?>
zspencer at zacharyspencer dot com
25-Sep-2008 05:14
Interesting to note, when passing an empty value into addChild (For instance from a null result from a database query) it assumes that you want to have an actual node instead of a string value.

Example:
<?php
$empty_node
='';
$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('empty_node',$empty_node);
print_r($xml);
/*
SimpleXMLElement Object
 {
   [empty_node] => SimpleXMLElement Object
    {
      [0] =>
     }
 }

*/
?>

I haven't figured out a way around this yet, any hints?
jacob at 33i dot com dot au
20-Aug-2008 09:56
@kobrasrealm at gmail dot com

there is no lack of deleteChild function, you should use the php function unset()

<?php
unset($myxml->book[0]->page[22]);
unset(
$myxml->book[1]->page);
?>
essen at dev-extend dot eu
18-Jul-2008 12:06
Easy and fast deleting of a node:

<?php

$oNode
= dom_import_simplexml($oSimpleXMLNodeToDelete);
$oNode->parentNode->removeChild($oNode);

?>

The node can have childs, attributes, and be anywhere in your document, it'll get deleted. The deletion will appear immediately in your SimpleXML object after calling removeChild, there's nothing else to do.
kobrasrealm at gmail dot com
29-Jun-2008 05:22
Here's a handy workaround to accommodate the lack of a $xml->deleteChild() function. It's not perfect, but it's a start (and it works for what I'm using it for):

<?php
// Workaround by Kobra.
function simplexml_deleteChild($parent, $childname, $parentname)
{
$temp = simplexml_load_string(str_replace("#","?","<#xml version=\"1.0\"#>\n<".$parentname.">\n</".$parentname.">"));
foreach(
$parent as $t)
{
  if(
$t->getName() != $childname)
  {
 
$name = $t->getName();
 
$value = eval("return \$parent->".$name.";");
 
$temp->addChild($t->getName(), $value);
  }
}
return
$temp;
}

?>

I have not tested this with multi-level XML files; but like I said, it's a start.
danz at gethitz dot info
30-Jan-2008 09:12
Object cloning ...

So using the 'clone' keyword here lets you work on $new separately, and attributes added to $new don't show up in $sxe

without the 'clone' all changes to $new will be reflected in the larger $sxe tree

                $new = clone $sxe->AddChild("comment",$comment);
                $new->AddAttribute("name",$name);
                $new->AddAttribute("url",$url);
                $new->AddAttribute("ip",$ip);
                $new->AddAttribute("time",$time);
chicken dot ofeathers at gmail dot com
19-Jan-2008 03:57
Correct namespace usage:

<?php
$xml
= new SimpleXMLElement('<root xmlns:itunes="http://example.com"/>');
$n = $xml->addChild("subtitle", "My Subtitle", " http://example.com");
?>

Incorrect namespace usage:

<?php
$xml
= new SimpleXMLElement('<root xmlns:itunes="http://example.com"/>');
$n = $xml->addChild("subtitle", "My Subtitle", " itunes");
?>

The latter incorrect usage results in the following superfluous xmlns attribute:

<itunes:subtitle xmlns:itunes="itunes">My Subtitle</itunes:subtitle>

Whereas all you want is this:

<itunes:subtitle>My Subtitle</itunes:subtitle>
ron @ rotflol dot cx
11-Jul-2007 12:37
Replacing a node is an easy mod of the simplexml_append

function simplexml_replace(SimpleXMLElement $parent, SimpleXMLElement $new_child){
   $node1 = dom_import_simplexml($parent);
   $dom_sxe = dom_import_simplexml($new_child);
   $node2 = $node1->ownerDocument->importNode($dom_sxe, true);
   $node1->parentNode->replaceChild($node2,$node1);
}
r dot versluis at millipede dot nl
22-May-2007 09:23
<?php
// phpversion <= 5.1.2

function simplexml_addChild($parent, $name, $value=''){
   
$new_child = new SimpleXMLElement("<$name>$value</$name>");
   
$node1 = dom_import_simplexml($parent);
   
$dom_sxe = dom_import_simplexml($new_child);
   
$node2 = $node1->ownerDocument->importNode($dom_sxe, true);
   
$node1->appendChild($node2);
    return
simplexml_import_dom($node2);
}

function
simplexml_addAttribute($parent, $name, $value=''){
   
$node1 = dom_import_simplexml($parent);
   
$node1->setAttribute($name,$value);
    return
simplexml_import_dom($node1);
}

?>
l dot j dot peters at student dot utwente dot nl
12-Mar-2007 09:49
Rob Richards and I have come up with a very easy way to append one SimpleXML tree to another:
<?php
function simplexml_append(SimpleXMLElement $parent, SimpleXMLElement $new_child){
  
$node1 = dom_import_simplexml($parent);
  
$dom_sxe = dom_import_simplexml($new_child);
  
$node2 = $node1->ownerDocument->importNode($dom_sxe, true);
  
$node1->appendChild($node2);
}
?>
And adding a textnode is also easy:
<?php
//$sxe1 (refers to SimpleXMLElement)
$node1 = dom_import_simplexml($sxe1);
$node1->appendChild(new DOMText("my text"));
?>

Ofcourse, you could use this to extend the SimpleXMLElement class and overwrite and improve the existing addChild function.

Have fun, Luuk Peters.

 
show source | credits | sitemap | contact | advertising | mirror sites