我有这段代码可以读取Docx文件的XML:
$zip = new ZipArchive;
$zip->open($fileName);
$xmlDoc = $zip->getFromName('word/document.xml');
从此开始,如何使用DOMDocument对其进行修改?
我的目标是使用PHP的本机功能,如果有更好的功能,您可以给我一个解释,为什么使用其他功能代替DOMDocument。?
编辑
为了获得更好的解释,这里是“完整”代码:
$zip = new ZipArchive;
$zip->open("MyFile.docx");
if (($index = $zip->locateName("word/document.xml")) !== false) {
$text = $zip->getFromIndex($index);
$xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
$xmlText = $xml->saveXML();
}
$zip->close();
现在我需要删除一些节点,但是该文件已使用PHPWord修改,并且已满]
<w:t>First text</w:t>
<w:t>Second text</w:t>
<w:t>Third text</w:t>
。
我只需要删除其中之一,但我不知道该如何捕捉我需要的那个。
如果您扩展了到目前为止的代码,则可以看到如何查找各种文本。您必须使用新的DOMXpath对象注册名称空间w,然后可以使用<w:t>
搜索文档中的任何元素(在本例中为//w:t
的元素)。
此代码仅循环遍历它们并显示值,但不确定要对内容做什么...
$zip = new ZipArchive;
$zip->open("text.docx");
if (($index = $zip->locateName("word/document.xml")) !== false) {
$text = $zip->getFromIndex($index);
$xml = new DOMDocument();
$xml->loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
$xmlText = $xml->saveXML();
$xp = new DOMXPath($xml);
// Register main namespace (w)
$xp->registerNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
// Search for <w:t> elements
$text = $xp->query("//w:t");
foreach ($text as $entry) {
echo $entry->textContent.PHP_EOL;
}
}
$zip->close();