Search code examples
xmltemplateslarge-data

PHP creating large xml with same options but different values each time


I have a website that has a large form (50+ fields).

Each field is mandatory. After the form is submitted, I need to put all values into an xml file.

The XML file will always have the same elements, but with different values.

I've been trying to find the best way to create them and I thought there would be some sort of templating for XML.

What is the best way to do this?

Currently I'm doing it like this:

$m_content_tag = $doc->createElement("m_content");
$m_content_tag = $message_tag->appendChild($m_content_tag);
$b_control_tag = $doc->createElement("b_control");
$b_control_tag = $m_content_tag->appendChild($b_control_tag);
$b_control_tag->appendChild($doc->createElement('service_provider_reference_number'));
$b_control_tag->appendChild($doc->createElement('intermediary_case_reference_number'));

For each element, which is getting quite hard to manage.


Solution

  • Like Symfony you could use TWIG to handle the rendering your XML template. This will let you keep all the XML in a separate file then you can just pass an assoc array of your validated fields to TWIG's render method and TWIG will handle the rest. You can even break down the different XML sections into different files and include them dynamically as blocks.

    XML Template:

    <?xml version="1.0"?>
    <root>
        <field_1>{{ var1 }}</field_1>
        <field_2>{{ var2 }}</field_2>
        <field_3>
                 {% for subvar in var3 %}
                     <subfield_3>{{ subvar }}</subfield_3>
                 {% endfor %}
        </field_3>
    </root>
    

    PHP Code:

    //Validate fields into assoc array
    $fields['var1'] = 'Some Value';
    $fields['var2'] = 'Some other Value';
    $fields['var3'] = array(1,2,3,4);
    
    //Set up TWIG
    $loader = new Twig_Loader_Filesystem('/path/to/templates');
    $twig = new Twig_Environment($loader, array(
        'cache' => '/path/to/compilation_cache',
    ));
    
    //Render template
    echo $twig->render('xml_template.xml', $fields);