Friday, May 13, 2016

Creating simple xml file using Drupal

Here is the snippet to create an xml file using our custom module. We can customise tags, attributes and values for the xml elements.

    $dom = new DomDocument('1.0');

    //add root - <parent>
    $parent = $dom->appendChild($dom->createElement('parent'));

    //set attributes to <parent> tag
    $parent->setAttribute("name", "parent1");

    //add <child1> element to <parent>
    $child1 = $parent->appendChild($dom->createElement('child1'));

    //add elements to <child1>
    $schema = $child1->appendChild($dom->createElement('schema'));
    $schema->appendChild($dom->createTextNode('Schema Name')); //add <title> text node element to <schema>
    $schemaversion = $child1->appendChild($dom->createElement('schemaversion'));

    //add <child2> element to <parent>              
    $child2 = $parent->appendChild($dom->createElement('child2'));
    //add elements to <child2>
    $listr = array('value1','value2');

    $i = 1;
    foreach ($listr as $parent => $href) {
                $baby = $child2->appendChild($dom->createElement('baby'));
                $baby->setAttribute("href", $href);
                $baby->setAttribute("type", "webcontent");
                $baby->setAttribute("intendeduse", "unspecified");
                $babyfile = $baby->appendChild($dom->createElement('file'));
                $babyfile->setAttribute("href", $href);

    // generate xml
    $dom->formatOutput = true; // set the formatOutput attribute of dom Document to true
    $test1 = $dom->saveXML(); // save XML as string or file
    $dom->save('simple.xml'); // save as file