update page now
Laravel Live Japan

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addChild Adiciona um elemento filho à um nó XML

Descrição

public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement

Adiciona um elemento filho ao nó e retorna um elemento SimpleXML do nó filho.

Parâmetros

qualifiedName

O nome do elemento filho à ser adicionado.

value

Se especificado, o valor do elemento filho.

namespace

Se especificado, o namespace ao qual o elemento filho pertence.

Valor Retornado

O método addChild retorna um objeto SimpleXMLElement representando o filho adicionado ao nó XML em caso de sucesso; null em caso de falha.

Exemplos

Nota:

Os exemplos listados podem incluir o arquivo examples/simplexml-data.php, que referem-se a uma string XML encontrada no primeiro exemplo do guia de uso básico.

Exemplo #1 Adiciona atributos e filhos à um elemento SimpleXML

<?php

include 'examples/simplexml-data.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('tipo', 'documentário');

$filme = $sxe->addChild('filme');
$filme->addChild('titulo', 'PHP2: Mais Estórias de Interpretadores');
$filme->addChild('resumo', 'É tudo é sobre as pessoas que fazem isso funcionar.');

$personagens = $filme->addChild('personagens');
$personagem = $personagens->addChild('personagem');
$personagem->addChild('nome', 'Sr. Interpretador');
$personagem->addChild('ator', 'Fulano de Tal');

$classificacao = $filme->addChild('classificacao', '5');
$classificacao->addAttribute('tipo', 'estrelas');

echo
$sxe->asXML();

?>

O exemplo acima produzirá algo semelhante a:

<?xml version="1.0" standalone="yes"?>
<filmes tipo="documentário">
 <filme>
  <titulo>PHP: Nos Bastidores do Interpretador</titulo>
  <personagens>
   <personagem>
    <nome>Srta. Codificadora</nome>
    <ator>Onlivia Actora</ator>
   </personagem>
   <personagem>
    <nome>Sr. Codificador</nome>
    <ator>El Act&#xF3;r</ator>
   </personagem>
  </personagens>
  <resumo>
   Então, essa linguagem. Se parece com uma linguagem de programação. Ou seria uma
   liguagem de scripts? Tudo é revelado nesta emocionante paródia de terror
   de um documentário.
  </resumo>
  <melhores-frases>
   <frase>O PHP resolve todos os meus problemas!</frase>
  </melhores-frases>
  <classificacao tipo="gostei">7</classificacao>
  <classificacao tipo="estrelas">5</classificacao>
 </filme>
 <filme>
  <titulo>PHP2: Mais Estórias de Interpretadores</titulo>
  <resumo>É tudo é sobre as pessoas que fazem isso funcionar.</resumo>
  <personagens>
   <personagem>
    <nome>Sr. Interpretador</nome>
    <ator>Fulano de Tal</ator>
   </personagem>
  </personagens>
  <classificacao tipo="estrelas">5</classificacao>
 </filme>
</filmes>

Veja Também

adicionar nota

Notas de Usuários 6 notes

up
42
frosty dot z at freesbee dot fr
12 years 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 :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
up
27
alex dot feraud at gmail dot com
14 years ago
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);
            }
        }
    }
}
?>
up
4
nwarap
8 years ago
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
up
12
johninen at gmail dot com
10 years ago
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

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.
up
7
Volker Grabsch
14 years ago
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 "&amp;" 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
1
fluxlicious at gmail dot com
2 years ago
The class below allows you to write CDATA and to add additional attributes.

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
    public function addChildWithCData($name, $value)
    {
        $child = parent::addChild($name);
        $element = dom_import_simplexml($child);
        $docOwner = $element->ownerDocument;
        $element->appendChild($docOwner->createCDATASection($value));
        return $child;
    }
}
?>

Example:
<?php
        $xml = new SimpleXMLElementExtended('<xml></xml>');
        $content = $xml->addChildWithCData('content', 'Title of the page');
        $content->addAttribute('id', 1);
        $content->addAttribute('enabled', 'true');

        // Output:
        // <xml>
        //   <content id="1" enabled="true"><![CDATA[Title of the page]]></content>
        // </xml>
?>
To Top