Repeat structures automatically with simpleXML?

I am defining form elements in a simple XML structure like this:

<subtab id="page_background" label="Page Background" prefix="page">
   <input label="Background color" field="bgcolor" type="color"/>
   <input label="Background image" field="bgimage" type="image"/>
   <space />
 </subtab>
   etc.

      

I have large blocks containing absolutely identical information, for example. form fields to define the page background, content area, top bar, etc. This makes the XML file very cumbersome to work with and view.

Is there an embedded XML "Copy + Paste" construct / command / operator that tells the XML parser - in my case simpleXML - to find the content of a particular branch from another?

In pseudocode:

<subtab id="content_background" copyFrom="../page_background">
<!-- sub-elements from "page_background" are magically copied here 
     by the parser -->
</subtab>

      

+2


source to share


2 answers


XML is just a format, so there is no copy command. XSLT can do this, but it's probably too complex for your needs.

My advice: create a PHP function that will add your templated elements. For example:



function default_elements(SimpleXMLElement $node)
{
    $default = array(
        'input' => array(
            array('label'=>"Background color", 'field'=>"bgcolor", 'type'=>"color"),
            array('label'=>"Background image", 'field'=>"bgimage", 'type'=>"image")
        ),
        'space' => array(
            array()
        )
    );

    foreach ($default as $name => $elements)
    {
        foreach ($elements as $attrs)
        {
            $new = $node->addChild($name);
            foreach ($attrs as $k => $v)
            {
                $new[$k] = $v;
            }
        }
    }
}

      

+4


source


You have to create a SimpleXmlElement with the format and use clone , each time updating any changed attributes or bleeds.



0


source







All Articles