$dir = "temp/docx";
$errors = array();
$zip = new ZipArchive;
if($zip->open($file_path) === false){
$errors[] = 'Failed to open file';
}
if (empty($errors)) {
$zip->extractTo($dir,"word/document.xml");
$zip->close();
$files = scandir($dir);
print_r($files);
好的,基本上由于某种原因,提取不起作用。看到文件夹是空的后,我决定做一个扫描程序,看看它们是否在 php 完成后删除。无。$files变量不输出任何内容(当然除了 .. 和 .(。
zip实际上是一个docx文件,在明确检查错误后,php似乎认为zip_open有效,但我不确定这是否只是一个误报。
我想知道这是否是由于这实际上是一个docx文件,我需要将其显式保存为服务器上的zip文件。或者可能是因为这在上传后直接发生,并且临时文件在能够对其进行任何操作之前被删除(我想这不太可能,因为其他格式工作正常(。也许我的两个假设都不接近,或者我有可能把整件事写错了。有什么帮助吗?
你来了:
<?php
/*Name of the document file*/
$document = 'demo.docx';
/*Directory*/
$dir = "temp/docx/";
/**Function to extract text*/
function extracttext($filename, $action) {
//Check for extension
$ext = end(explode('.', $filename));
//Check if DOCX file
if($ext == 'docx'){
$dataFile = "word/document.xml";
//else it's probebly an ODT file
} else {
$dataFile = "content.xml";
}
//Create a new ZIP archive object
$zip = new ZipArchive;
// Open the archive file
if (true === $zip->open($filename)) {
// If successful, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// Index found! Now read it to a string
$text = $zip->getFromIndex($index);
// Load XML from a string
// Ignore errors and warnings
$xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
if($action == "save"){
// Save xml to file
file_put_contents($dir ."word/document.xml", $xml->saveXML());
return "File succesfully saved.";
} else if($action == "text"){
// Remove XML formatting tags and return the text
return strip_tags($xml->saveXML());
}
}
//Close the archive file
$zip->close();
}
// In case of failure return a message
return "File not found";
}
//Save xml file
echo extracttext($document, "save");
//Echo text from file
echo extracttext($document, "text");
?>