Search code examples
phpxmlsimplexml

How do I add an XMLElement to an XMLElement?


I want to create some XML dynamically and I wonder how I could add an XMLElement to an XMLElement?

Here's my code:

    $table = new SimpleXMLElement("<table></table>");
    $tableRow = new SimpleXMLElement("<tr></tr>");

    $count = count($this->dataSource->columns);
    for ($i = 0; $i < $count; $i++)
    {
        $tableRow->addChild("<th></th>","Hi!") 
    }

    $table->addChild($tableRow); // Not good, but this is what I want to do.

Solution

  • I haven't found the answer to my question. I've coded a class which inherit from SimpleXmlElement and added a method "addChildElement(XElement $element)". The method take an XElement in parameter and add it (and its childs) recursively. I don't know if this is the best way to do it but it seems to work pretty well for me. Tell me if something is wrong with this function. Note that you can't modify an XElement after you've added it to the xml, but I'm working on it.

    class XElement extends SimpleXMLElement
    {
        /**
         * Add an XElement to an XElement.
         * @param XElement $element
         * @return void
         */
        public function addChildElement(XElement $element)
        {
            // TODO Handle namespaces
            $addedElement = $this->addChild($element->getName(), (string)$element);
    
            foreach ($element->children() as $node)
            {
                $addedElement->addChildElement($node);
            }
        }
    }
    

    How to use:

    $tableRow = new XElement("<tr></tr>");
    $asd = new XElement("<tr2></tr2>");
    $asd2 = new XElement("<tr3></tr3>");
    $asd->addChildElement($asd2);
    $tableRow->addChildElement($asd);
    

    This wont work, but I'm working on it:

    $tableRow = new XElement("<tr></tr>");
    $asd = new XElement("<tr2></tr2>");
    $asd2 = new XElement("<tr3></tr3>");
    $tableRow->addChildElement($asd);
    $asd->addChildElement($asd2);