我将XML文件从DOCX(ZIP存档)解析为xml_parse_into_struct
的数组。结果如下。
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
)
)
经过一些更改后,我需要先将其转换回XML文件(然后转换为DOCX文件)。这是我需要的XML文件的结构:
<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>
我该怎么做?
答案 0 :(得分:0)
最后,编写了一个简单易用的函数,它将上面的数组转换为XML格式。这是解决方案:
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;
}