0

I parsed the XML file from DOCX (ZIP archive) to array by xml_parse_into_struct. Here is the result.

Array
(

[0] => Array
    (
        [tag] => W:DOCUMENT
        [type] => open
        [level] => 1
        [attributes] => Array
            (
                [XMLNS:WPC] => http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas
            )
    )

[1] => Array
    (
        [tag] => W:BODY
        [type] => open
        [level] => 2
    )

[2] => Array
    (
        [tag] => W:P
        [type] => open
        [level] => 3
        [attributes] => Array
            (
                [W:RSIDR] => 00383EED
                [W:RSIDRDEFAULT] => 00383EED
                [W:RSIDP] => 001F2B24
            )
    )
...
[15] => Array
    (
        [tag] => W:P
        [type] => close
        [level] => 3
    )
...
[2348] => Array
    (
        [tag] => W:BODY
        [type] => close
        [level] => 2
    )

[2349] => Array
    (
        [tag] => W:DOCUMENT
        [type] => close
        [level] => 1
    )
)

After some changes I need to convert it back to XML file first (and then to a DOCX file). Here is the structure of XML file I need:

<w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas">
    <w:body>
        <w:p w:rsidR="00383EED" w:rsidRDefault="00383EED" w:rsidP="001F2B24">...</w:p>
    ...
    </w:body>
</w:document>

How can I do this?

Tom
  • 4,257
  • 6
  • 33
  • 49
maaak7
  • 15
  • 6
  • 1
    http://stackoverflow.com/a/1397164/2359679 – hassan Apr 13 '17 at 08:07
  • hi @hassan. thank you for quick reply. but it's not the result I need. I know how to do the simple XML file from an array. but here I need to do a XML file with children and attributes. – maaak7 Apr 13 '17 at 08:10
  • please update your question with a valid executable php array – hassan Apr 13 '17 at 08:11

1 Answers1

0

Finally, wrote small and easy function, which will convert array as above to XML format. Here is the solution:

public function array_to_xml($array)
{
    $xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';

    foreach ($array as $tag) {
        $xml .= '<';
        $xml .= ($tag['type'] === 'close') ? '/' . $tag['tag'] : $tag['tag'];

        if (isset($tag['attributes'])) {
            foreach ($tag['attributes'] as $key => $attr) {
                $xml .= ' ' . $key . '="' . $attr . '"';
            }
        }

        if ($tag['type'] === 'complete' && !isset($tag['value'])) {
            $xml .= '/';
        }
        $xml .= '>';

        if (isset($tag['value'])) {
            $xml .= $tag['value'] . '</' . $tag['tag'] . '>';
        }
    }

    return $xml;
}
maaak7
  • 15
  • 6