SimpleXML how to prepend a child in a node?

Asked
Active3 hr before
Viewed126 times

5 Answers

child
90%

Here's how to extend SimpleXMLElement with a new method prependChild():, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Create a new SimpleXMLElement, copy over the attributes, then add your new node, then add all the children of your original node after that, then replace the original with the new one.,update: After a bit more looking through the docs, I'd suggest something like the following (assuming you still want to stick with SimpleXML for the most part, otherwise, just use DOM directly for everything):

Here's how to extend SimpleXMLElement with a new method prependChild():

class my_node extends SimpleXMLElement
{
    public function prependChild($name, $value)
    {
        $dom = dom_import_simplexml($this);

        $new = $dom->insertBefore(
            $dom->ownerDocument->createElement($name, $value),
            $dom->firstChild
        );

        return simplexml_import_dom($new, get_class($this));
    }
}

$actors = simplexml_load_string(
    '<actors>
        <actor>Al Pacino</actor>
        <actor>Zsa Zsa Gabor</actor>
    </actors>',
    'my_node'
);

$actors->addChild('actor', 'John Doe - last');
$actors->prependChild('actor', 'John Doe - first');

die($actors->asXML());
load more v
88%

SimpleXMLElement::addChild — Adds a child element to the XML node , Adds a child element to the node and returns a SimpleXMLElement of the child. ,SimpleXMLElement::addAttribute() - Adds an attribute to the SimpleXML element, The addChild method returns a SimpleXMLElement object representing the child added to the XML node on success; null on failure.

<?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>
72%

If I add a child into node0, it places himself always after the </node3>. I’ve changed the position on the php xml generation code, but it’s ignored.,Let’s say we wanted to add a <node2> exactly between </node1> and <node3> . How can we do that by using simpleXML ?,The method would have to create a DOM document from the SimpleXML object, add the child then re-import into SimpleXML.,If we add children to that node, the magic happens, and somehow, the xml structure changes from <node/> TO <node> </node>;

Given the following XML for example:

<?xml version="1.0" encoding="UTF-8"?>
<node0>
   <node1>
   </node1>
   <node3>
   </node3>
</node0>
load more v
65%

The following is a function to insert a new SimpleXMLElement after some other SimpleXMLElement. Since this isn't directly possible with SimpleXML, it uses some DOM classes/methods behind-the-scenes to get the job done.,Additional the functions simplexml_load_*() has a second parameter string $class_name = "SimpleXMLElement" to specify the class of the object to get returned. Thats not a specific feature of the functions, because you can "use" something very similar with usual instanciation too,simplexml_load_string() (as the name suggest) load xml from a string and returns an object of SimepleXMLElement. There is no difference between this and using just the usual constructor of the class. ,SimpleXML::__construct() has an additional parameter (the third one) bool $data_is_url = false. If this is true the behavior is the same as simplexml_load_file() (in conjunction with the common stream wrappers). Thus both simplexml_load_*()-functions cover the same functionality as SimpleXML::__construct().

say I have XML:

<root>
   <nodeA />
   <nodeA />
   <nodeA />
   <nodeC />
   <nodeC />
   <nodeC />
</root>

How do I insert "nodeB" between As and Cs? In PHP, preferably via SimpleXML? Like:

<root>
   <nodeA />
   <nodeA />
   <nodeA />
   <nodeB />
   <nodeC />
   <nodeC />
   <nodeC />
</root>
load more v
75%

Pre-requisite: Read XML BasicsThe SimpleXMLElement::children() function is an inbuilt function in PHP which returns children of a given node in a SimpleXML object. ,Return Value: This function returns a SimpleXMLElement object.Note: This function is available on PHP 5.0.1 and newer version.Below programs illustrate the SimpleXMLElement::children() function in PHP:Program 1: This program displays the value of child node. ,PHP | SimpleXMLElement children() Function,PHP | SimpleXMLElement attributes() Function

Syntax:  

SimpleXMLElement SimpleXMLElement::children($namespace, $is_prefix)

Output: 

Child node: Geeks123
Child node: GeeksforGeeks
Child node: +91 - XXXXXXXXXX
Child node: Noida, UP, India

Output: 

Child node: username => Geeks123
Child node: name => GeeksforGeeks
Child node: phone => +91 - XXXXXXXXXX
Child node: address => Noida, UP, India

Output: 

Child name: username => Geeks123
parameter: font - color => green
parameter: font => awesome - fonts
parameter: font - size => 72 px
Child name: name => GeeksforGeeks
parameter: font - color => blue
parameter: font => awesome - fonts
parameter: font - size => 36 px
Child name: phone => +91 - XXXXXXXXXX
parameter: font - color => blue
parameter: type => number
parameter: font => awesome - fonts
parameter: font - size => 24 px
Child name: address => Noida, UP, India
parameter: font - color => blue
parameter: font => awesome - fonts
parameter: font - size => 24 px
load more v

Other "child-undefined" queries related to "SimpleXML how to prepend a child in a node?"