【问题标题】:Not able to update word/rels/document.xml.rels using PHP ZipArchive无法使用 PHP ZipArchive 更新 word/rels/document.xml.rels
【发布时间】:2010-06-24 07:43:43
【问题描述】:

我正在尝试使用 PHP 将二进制数据作为图像加载到 Word 文档 (Opem XML) 中,以便以后与 XSLT 一起使用。

将 Word 文档作为 PHP ZipArchive 打开后,我能够成功地将图像加载到 word/media 文件夹中,并且还可以更新 word/document.xml 文件.但我无法更新 word/rels/document.xml.rels 文件中的<Relationships/>

我已经交叉检查了 xml 格式是否正确。

以下是我尝试使用的代码sn-p,

        $zipArchive=new ZipArchive();
    $zipArchive->open($pathToDoc);
    $imagePre="image";
    $relIdPre="rId";
    $index=100;

    $nodeList = $reportDOM->getElementsByTagName("Node");
    $i=0;

    foreach($nodeList as $node) {
        $divList = $node->getElementsByTagName("*");

        foreach ($divList as $divNode) {
            if (strncasecmp($divNode->nodeName, "wizChart", 8) == 0) {
                $imgData=$divNode->getAttribute("src");
                $imgData=base64_decode(substr($imgData,22));

                    $zipArchive->
addFromString("word/media/".$imagePre."".$index.".png",$imgData);
                $fp=$zipArchive->getStream("word/_rels/document.xml.rels");

                $contents='';
                while (!feof($fp)) {
                    $contents .= fread($fp, 2);
                }
                $serviceOutput=new DOMDocument();
                $serviceOutput->loadXML($contents);
                $serviceList=$serviceOutput->getElementsByTagName("Relationships");

                $element=$serviceOutput->createElement("Relationship");
                $element->setAttribute("Id",$relIdPre."".$index);
                $element->setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
                $element->setAttribute("Target","word/media/".$imagePre."".$index.".png");

                foreach ($serviceList as $serviceNode) {
                $serviceNode->appendChild($element);
                }

                $zipArchive->addEmptyDir("word/_rels/");
                $zipArchive->addFromString("word/_rels/document.xml.rels", $serviceOutput->saveXML());
                $index++;
            }       
        }
    }
    $zipArchive->close();

谁能建议我做错了什么?

【问题讨论】:

  • 您并没有准确地说出正在发生(或未发生)的事情。文件没有变化吗?
  • 如果我注释掉试图将 xml 节点添加到 docmuents.xml.rels 文件的部分,图像将保存到 word 文档中。但是,如果我尝试将这些关系添加到 .rels 文件中,即使图像也不会保存。我正在使用以下链接中提到的 PHP 代码 msdn.microsoft.com/en-us/library/ee840137(office.12).aspx 并尝试在将 $newContent 应用于 word/document.xml 之前将图像添加到 $outputDocument

标签: php openxml ziparchive


【解决方案1】:

您在添加 PNG 时也会添加新的内容类型,因此您需要在 [Content_Types].xml 中进行设置。详情请见Is it possible to add some data to a Word document?

【讨论】:

  • 感谢您的帖子,但 [Content-Types].xml 中已经存在 PNG 内容类型。正如我之前所说,我可以将图像添加到 Word 文档中。我无法将关系添加到 _rels/document.xml.rels 文件。该代码仅在我尝试添加关系时才起作用,如果我注释掉该部分,我可以将图像添加到文档中。
猜你喜欢
  • 2023-01-10
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多